Are deferred functions called when calling log.Fatalln?
Asked Answered
M

2

24
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, is db.Close() still being called?

Martellato answered 26/7, 2013 at 18:35 Comment(1)
No. If you need deferred functions running, use log.PaniclnSpineless
B
38

No, the deferred functions aren't run.

Here's the description of log.Fatal :

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

log.Fatal calls os.Exit, whose description is here :

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

Demonstration

If you really need to properly close resources or do some tasks before the program finishes, then don't use log.Fatal.

Bike answered 26/7, 2013 at 18:37 Comment(1)
If calling log.Fatalln in main(), you could instead call log.Println followed by return.Scalade
A
5

If you want deferred functions to be considered use "log.Panic", "log.Panicf" or "log.Panicln"

Appenzell answered 31/3, 2022 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.