Home > Backend Development > Golang > Do Deferred Functions Execute After `log.Fatalln` in Go?

Do Deferred Functions Execute After `log.Fatalln` in Go?

Mary-Kate Olsen
Release: 2024-12-04 16:24:16
Original
215 people have browsed it

Do Deferred Functions Execute After `log.Fatalln` in Go?

Log.Fatalln and Deferred Function Execution

In Go programs, deferred functions are automatically called when the enclosing function returns. However, a common question arises: are deferred functions executed when the log.Fatalln function is invoked?

Understanding log.Fatalln

The log.Fatalln function is a member of the standard Go logging package. It logs the provided message and then immediately calls os.Exit(1) to terminate the program. The os.Exit function, in turn, prevents the execution of any deferred functions.

Deferred Function Execution in Case of log.Fatalln

Therefore, the answer to the question is no. Deferred functions are not executed when log.Fatalln is called. This is because log.Fatalln terminates the program abruptly, bypassing the execution of deferred functions.

This behavior is documented in the description of log.Fatal, the function equivalent to log.Fatalln:

Fatal is equivalent to Print() followed by a call to os.Exit(1).
Copy after login

Practical Demonstration

The following code demonstrates this behavior:

db, err := sql.Open("postgres", "…")
if err != nil {
    log.Fatalln(err)
}
defer db.Close()

tpl, err := template.ParseGlob("")
if err != nil {
    log.Fatalln(err)
}
Copy after login

If template.ParseGlob("") returns an error, the call to db.Close() will not be executed because log.Fatalln will terminate the program before reaching that line.

Alternative Approach

If you need to ensure that cleanup tasks are performed before the program terminates, you should consider using other logging functions, such as log.Print or log.Println, which do not terminate the program.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template