Commits

Miki Tebeka committed c2f6d3f

Handle panics in handlers

Comments (0)

Files changed (3)

 package atexit
 
 import (
+	"fmt"
 	"os"
 )
 
 var handlers = []func(){}
 
+func runHandler(handler func()) {
+	defer func() {
+		if err := recover(); err != nil {
+			fmt.Fprintln(os.Stderr, "error: atexit handler error:", err)
+		}
+	}()
+
+	handler()
+}
+
 // Exit runs all the atexit handlers and them terminates the program using os.Exit(code)
 func Exit(code int) {
 	for _, handler := range handlers {
-		handler()
+		runHandler(handler)
 	}
 
 	os.Exit(code)
 	err := exec.Command("./6.out", filename, arg).Run()
 	if wmsg, ok := err.(*os.Waitmsg); ok {
 		if wmsg.ExitStatus() != 1 {
-			t.Fatalf("bad exit status (%s), should be 1", wmsg.ExitStatus())
+			t.Fatalf("bad exit status (%d), should be 1", wmsg.ExitStatus())
 		}
 	} else {
 		t.Fatalf("bad exit status 0, should be 1")
 import (
 	atexit "./_obj/atexit"
 	"flag"
+	"fmt"
 	"io/ioutil"
 )
 
 	ioutil.WriteFile(outfile, []byte(data), 0666)
 }
 
+func badHandler() {
+	n := 0
+	fmt.Println(1/n)
+}
+
 func main() {
 	flag.Parse()
 	outfile = flag.Arg(0)
 	data = flag.Arg(1)
 
 	atexit.Register(handler)
+	atexit.Register(badHandler)
 	atexit.Exit(1)
 }