dongyuans61046 2016-03-14 20:02
浏览 567

我应该何时在golang中使用panic vs log.fatalln()?

From the documentation on log.Fatalln():

func Fatalln(v ...interface{}) Fatalln is equivalent to Println() followed by a call to os.Exit(1).

The source code for 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  }

It seems the main difference is whether or now the error is recoverable (since you can recover a panic) - is there anything more significantly different between these?

Panic's interface definition is:

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

It appears panic does not return anything.

Is that the primary difference? Otherwise, they seem to perform the same function in an application, assuming the panic is not recovered.

  • 写回答

2条回答 默认 最新

  • douhua1890 2016-03-14 20:22
    关注
    • 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.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?