os.Exit
or log.Fatal
and friends made in function using defer
CRT-D0011defer func(){...}(...)
will not run 58 } else {
59 fmt.Println(version)
60 }
61 os.Exit(exitOk) 62 }
63
64 // Event channel
Calls to os.Exit
or log.Fatal
and friends made in function with defer
statements do not execute those statements if control reaches the
os.Exit
or log.Fatal
and friends.
If the os.Exit
function happens in a goroutine, all the goroutines (including
the main one) will terminate immediately without executing any deferred statement.
Internally, log.Fatal
and friends (log.Fatalln
and log.Fatalf
) internally
uses os.Exit(1)
, which results in the immediate termination of the program
without executing the deferred statements.
It is recommended to handle such cases gracefully so that deferred statements are executed to necessary operations such as closing open file descriptors, cleanup, etc.
defer os.Remove(filename)
if bad {
log.Fatalf("something bad happened")
}
defer os.Remove(filename)
if bad {
log.Printf("something bad happened")
return // exits with "exit status 0"
}
retcode := 0
defer func() { os.Exit(retcode) }
defer os.Remove(filename)
if bad {
log.Printf("something bad happened")
retcode = 1
return // exits with "exit status 1" because of topmost `defer` call
}