Are deferred functions called when calling log.Fatalln?

孤街浪徒 提交于 2019-12-29 07:30:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17888610/are-deferred-functions-called-when-calling-log-fatalln

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!