恐慌与对数的结果有什么不同?

根据 日志的文档:

Fatalln (v... interface {}) Fatalln 等效于 Println () 然后调用 os。退出(1)。

返回文章页面法塔林的 源代码:

   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{})

看来恐慌并没有带来任何回报。

这是主要区别吗?否则,它们似乎在应用程序中执行相同的功能,假设恐慌没有被恢复。

47961 次浏览
  • The log message goes to the configured log output, while panic is only going to write to stderr.

  • Panic will print a stack trace, which may not be relevant to the error at all.

  • Defers will be executed when a program panics, but calling os.Exit exits immediately, and deferred functions can't be run.

In general, only use panic for programming errors, where the stack trace is important to the context of the error. If the message isn't targeted at the programmer, you're simply hiding the message in superfluous data.

panic is often used in little programs to just terminate the program once an error appears you don't know how to handle or don't want to handle. The downside of panic is exactly that: it'll terminate the program (mostly, unless you use recover). It's generally not good to use panic unless you intend to recover from it or unless something has happened you really can't recover from at all nor where you can gracefully terminate the program otherwise. Consider for example an API that offers you functionality but that API secretly has a panic somewhere and you notice that your program terminates in production due to this. Thus, the "outward API" of whatever code you write should recover from panics and return an error instead. The same thing applies to anything that terminates the program.

However, os.Exit() can't be recovered from nor does it execute defers.