os.Exit
or log.Fatal
and friends made in function using defer
CRT-D0011defer regLock.Unlock()
will not run355 cmd.ExtraFiles = files
356 err = cmd.Start()
357 if err != nil {
358 log.Fatalf("Restart: Failed to launch, error: %v", err)359 }
360
361 return
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
}