为了账号安全,请及时绑定邮箱和手机立即绑定

golang 中 panic 和 log.fatalln() 的结果有什么不同?

golang 中 panic 和 log.fatalln() 的结果有什么不同?

Go
侃侃尔雅 2021-12-20 19:10:15
从log.Fatalln()上的文档:func Fatalln(v ...interface{}) Fatalln 等价于 Println() 然后调用 os.Exit(1)。Fatalln的源代码:   310  // Fatalln is equivalent to Println() followed by a call to os.Exit(1).   311  func Fatalln(v ...interface{}) {   312      std.Output(2, fmt.Sprintln(v...))   313      os.Exit(1)   314  }似乎主要区别在于错误是否可恢复(因为您可以恢复恐慌) - 这些之间有什么更显着的不同吗?Panic的接口定义是:   215  // The panic built-in function stops normal execution of the current   216  // goroutine. When a function F calls panic, normal execution of F stops   217  // immediately. Any functions whose execution was deferred by F are run in   218  // the usual way, and then F returns to its caller. To the caller G, the   219  // invocation of F then behaves like a call to panic, terminating G's   220  // execution and running any deferred functions. This continues until all   221  // functions in the executing goroutine have stopped, in reverse order. At   222  // that point, the program is terminated and the error condition is reported,   223  // including the value of the argument to panic. This termination sequence   224  // is called panicking and can be controlled by the built-in function   225  // recover.   226  func panic(v interface{})看起来恐慌不会返回任何东西。这是主要区别吗?否则,它们似乎在应用程序中执行相同的功能,假设没有恢复恐慌。
查看完整描述

2 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

  • 日志消息进入配置的日志输出,而恐慌只会写入标准错误。

  • Panic 将打印堆栈跟踪,这可能与错误完全无关。

  • defers会在程序panic时执行,但调用会os.Exit立即退出,deferred的函数无法运行。

通常,仅panic用于编程错误,其中堆栈跟踪对错误的上下文很重要。如果消息不是针对程序员的,那么您只是将消息隐藏在多余的数据中。


查看完整回答
反对 回复 2021-12-20
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

panic通常用于小程序中,一旦出现错误,您不知道如何处理或不想处理,就终止程序。的缺点panic正是:它会终止程序(大多数情况下,除非您使用recover)。它通常不好使用,panic除非您打算从中恢复,或者除非发生了某些事情您根本无法恢复,否则您可以正常终止程序。例如,考虑一个为您提供功能的 API,但该 API 秘密地有一个panic地方,您会注意到您的程序因此而在生产中终止。因此,您编写的任何代码的“外部 API”都应该从恐慌中恢复并返回错误。同样的事情适用于终止程序的任何事情。

但是, os.Exit() 无法从中恢复,也不执行 defers。


查看完整回答
反对 回复 2021-12-20
  • 2 回答
  • 0 关注
  • 587 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号