Home >Backend Development >Golang >Will `defer` functions execute after a `log.Fatalln()` call in Go?

Will `defer` functions execute after a `log.Fatalln()` call in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 19:44:14432browse

Will `defer` functions execute after a `log.Fatalln()` call in Go?

Deferred Functions and log.Fatalln() Calls

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:

  • log.Fatalln() is equivalent to log.Print() followed by os.Exit(1).
  • os.Exit() causes the program to exit with the specified status code (in this case, 1 for failure).
  • Deferred functions (such as db.Close()) are not run when os.Exit() is called.

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!

Statement:
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