從文檔上log.Fatalln():什麼時候應該在golang中使用panic vs log.fatalln()?
FUNC Fatalln(V ...接口{})Fatalln相當於給println() 隨後通過調用os.Exit(1)。
的source code爲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 }
看來主要區別在於是否有錯誤,現在是可恢復的(因爲你可以恢復恐慌) - 還有什麼更顯著不同它們之間?
恐慌的接口definition是:
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{})
看來恐慌不返回任何東西。
這是主要的區別嗎?否則,他們似乎在應用程序中執行相同的功能,假設恐慌未被恢復。
考慮閱讀[官方博客](https://blog.golang.org/defer-panic-and-recover),其中恐慌和恢復很好地解釋 – pupizoid