调用log.Fatalln时是否调用延迟函数? [英] Are deferred functions called when calling log.Fatalln?

查看:944
本文介绍了调用log.Fatalln时是否调用延迟函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果 template.ParseGlob( )返回一个错误,是 db.Close()仍然被调用?

If template.ParseGlob("") returns an error, is db.Close() still being called?

推荐答案

不,延迟函数不会运行。

No, the deferred functions aren't run.

下面是 log.Fatal


致命等同于Print(),后跟调用os.Exit(1)。

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

log.Fatal 调用 os.Exit ,其描述为此处


退出导致当前程序以给定的状态码退出。
通常情况下,代码零表示成功,错误不为零。
程序立即终止;延期功能不运行。

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.

演示

如果您确实需要在程序结束前正确关闭资源或完成某些任务,请不要使用 log.Fatal

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

这篇关于调用log.Fatalln时是否调用延迟函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆