go - 何时使用 os.Exit() 和 panic()?

标签 go exit

有人能解释一下 os.Exit()panic() 之间的主要区别以及它们在 Go 中的实际使用方式吗?

最佳答案

首先,每当您有“如何在实践中使用”的问题时,一个好的开始方法是 search Go 源代码(或任何足够大的 Go 代码库,真的)和 package docs寻找答案。

现在,os.Exitpanic 是完全不同的。 panic在程序或其部分达到不可恢复状态时使用。

When panic is called, including implicitly for run-time errors such as indexing a slice out of bounds or failing a type assertion, it immediately stops execution of the current function and begins unwinding the stack of the goroutine, running any deferred functions along the way. If that unwinding reaches the top of the goroutine's stack, the program dies.

os.Exit 用于当您需要立即中止程序, 无法恢复或运行延迟清理语句,并且还会返回错误代码(其他程序可以用来报告发生的事情)。这在测试中很有用,当你已经知道一个测试失败后,另一个也会失败,所以你最好现在退出。这也可以在您的程序完成所有需要做的事情时使用,现在只需要退出,即在打印帮助消息之后。

大多数时候你不会使用 panic(你应该返回一个 error 代替),而且你几乎不需要 os.Exit 在测试中的某些情况之外以及用于快速终止程序。

关于go - 何时使用 os.Exit() 和 panic()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28472922/

相关文章:

json - 在golang中解析没有索引名称的json

go - 交换两个字符串(Golang)

php - PHP中的die()和exit()有什么区别?

c++ - 保持屏幕打开

java swing关闭窗口而不退出应用程序

dictionary - 从 slice 图中删除重复项

go - 为什么 Go 在写入封闭 channel 时会感到 panic ?

MongoDB Go 驱动程序无法正确解码嵌套文档

python - 在 tkinter 窗口中禁用退出(或 [ X ])

Perl 内置退出并在一个命令中打印