Deferred Function Execution with log.Fatalln()
In Go, deferred functions are executed when the surrounding function returns, even if it exits due to panic or os.Exit(). However, there are exceptions to this rule.
log.Fatalln() and Deferred Functions
When a program calls the log.Fatalln() function, it prints an error message and then immediately exits the program with an exit code of 1. Importantly, log.Fatalln() calls os.Exit(), which prevents the remaining code from executing.
Implications for Deferred Functions
This means that if a deferred function is registered after a call to log.Fatalln(), it will not be executed. This is because os.Exit() terminates the program immediately, without giving the runtime a chance to run the deferred functions.
Demonstration
Consider the following code:
db, err := sql.Open("postgres", "…") if err != nil { log.Fatalln(err) } defer db.Close() tpl, err := template.ParseGlob("") if err != nil { log.Fatalln(err) }
In this example, if the first log.Fatalln() call is executed due to an error opening the database connection, the deferred function db.Close() will not be called because the program exits immediately after the log.Fatalln() call.
Alternatives to log.Fatalln()
If you need to properly release resources or perform other tasks before the program exits, you should not use log.Fatalln(). Instead, you can use log.Println() or print the error message to the standard error stream and then call os.Exit() manually.
The above is the detailed content of Do Deferred Functions Execute After `log.Fatalln()` in Go?. For more information, please follow other related articles on the PHP Chinese website!