Home >Backend Development >Golang >Will `defer` functions execute after a `log.Fatalln()` call in Go?
Problem:
Consider the following Go 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) }
If template.ParseGlob("") returns an error, will the db.Close() function be called?
Answer:
No, the deferred functions will not be executed in this scenario.
Explanation:
log.Fatalln() is a logging function that prints an error message and then calls os.Exit(1) to terminate the program immediately. Here's a breakdown:
In the code snippet, if the call to template.ParseGlob("") fails and log.Fatalln() is triggered, the program will exit immediately. As a result, the deferred function db.Close() will not be executed, potentially leaving the database connection open.
Demonstration:
To illustrate this behavior, the following code can be executed:
package main import ( "log" "os" ) func main() { defer os.Exit(1) // Exit the program with status code 1 log.Fatalln("Program terminated early") }
Running this code will result in the error message being logged and the program exiting immediately, without any deferred functions being executed.
Avoidance:
To avoid issues with improperly closed resources or unhandled tasks, consider using log.Println() for error logging and handling errors gracefully without terminating the program.
The above is the detailed content of Will `defer` functions execute after a `log.Fatalln()` call in Go?. For more information, please follow other related articles on the PHP Chinese website!