golang 中 panic 和 log.fatalln() 的结果有什么不同?
技术问答
329 人阅读
|
0 人回复
|
2023-09-11
|
从log.Fatalln()文件:8 h' b- f9 u y, t+ u' e, x7 s. P4 w
func Fatalln(v …interface{}) Fatalln 等价于 Println() 然后调用 os.Exit(1)。
* l$ ?& D& v. W" O8 A% _6 tFatalln的源代码:# M @% W$ J1 {# F; W
310 /Fatalln is equivalent to Println() followed by a call to os.Exit(1). 311 func Fatalln(v ...interface{}std.Output(2,fmt.Sprintln(v...)) os.Exit(1) 314 }+ t5 I( q1 S+ y) B6 @, H
主要区别在于错误是否可以恢复(因为你可以恢复恐慌) - 这些有什么更显著的区别吗?
5 l. e8 q6 N! _# @: MPanic界面定义如下:& U4 E+ b1 ^ L. E) t' P
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 invocation of F then behaves like a call to panic,terminating G's 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 is called panicking and can be controlled by the built-in function recover. 226 func panic(v interface{})7 F7 m! g2 S/ z! Y* f/ g1 C0 I$ F+ C
恐慌似乎什么都不会回来。) ^$ ~( J/ ]" O2 m: `% w
这是主要区别吗?否则,假设恐慌没有恢复,它们似乎在应用程序中执行相同的功能。
$ c% F% Y# S9 |$ Z9 m% C* N N7 l1 V& W# s$ h( i
解决方案:
, [3 N: l+ I2 G y# h 日志信息进入配置的日志输出,恐慌只会写入标准错误。
" k, J% d B; GPanic 跟踪打印堆栈,这可能与错误无关。
7 J( y- J8 | D( Qdefers会在程序panic时执行,但调用会os.Exit立即退出,deferred的函数无法运行。通常,仅panic对于编程错误,堆栈跟踪对于错误的上下文非常重要。如果消息不是针对程序员的,你只是把消息藏在多余的数据里。 |
|
|
|
|
|