log.Fatal
相当于 Print
后调用 os.Exit(1)
import "log"
func main() {
defer func() {
log.Println("main exit")
}()
log.Println("main run")
log.Fatalln("Fatal err")
}
运行结果,程序直接退出 defer
没有被执行
# go run .
2023/09/05 19:20:30 main run
2023/09/05 19:20:30 Fatal err
exit status 1
panic
recover()
可以从panic中恢复
import "log"
func main() {
defer func() {
log.Println("main exit")
}()
log.Println("main run")
panic("panic err")
}
执行结果,panic会显示错误堆栈,defer
被执行,程序正常退出,可以使用log.Panic
记录消息
# go run .
2023/09/05 19:25:59 main run
2023/09/05 19:25:59 main exit
panic: panic err
goroutine 1 [running]:
main.main()
/mnt/d/ajanuw/go-demo/main.go:11 +0xac
exit status 2
标签:Fatal,run,log,golang,exit,main,panic
From: https://www.cnblogs.com/ajanuw/p/17680627.html