何时使用os.Exit()和panic()? [英] When to use os.Exit() and panic()?

查看:271
本文介绍了何时使用os.Exit()和panic()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could someone explain the key differences between os.Exit() and panic() and how they are used in practice in Go?

推荐答案

首先,每当您遇到如何在实践中使用它"问题时,一个好的开始方法是打包文档以获取答案.

First of all, whenever you have a "how it is used in practice" question, a good way to start is to search the Go source code (or any big enough Go code base, really), and the package docs for answers.

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

Now, os.Exit and panic are quite different. panic is used when the program, or its part, has reached an unrecoverable state.

当调用panic时,包括隐式地针对运行时错误(例如,对切片进行索引编制索引或失败类型断言),它将立即停止执行当前函数并开始展开goroutine的堆栈,运行任何一路延后的功能.如果解散到达goroutine栈的顶部,程序就会死掉.

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用于需要立即中止的程序,而无法恢复或运行延迟的清除语句,并且还返回错误代码(其他程序可以使用报告发生了什么).这在测试中很有用,当您已经知道一个测试失败后,另一个测试也会失败,因此您最好立即退出.当您的程序完成了它需要做的所有事情之后,现在只需要退出,即在打印帮助消息之后,也可以使用此功能.

os.Exit is used when you need to abort the program immediately, with no possibility of recovery or running a deferred clean-up statement, and also return an error code (that other programs can use to report what happened). This is useful in tests, when you already know that after this one test fails, the other will fail as well, so you might as well just exit now. This can also be used when your program has done everything it needed to do, and now just needs to exit, i.e. after printing a help message.

在大多数情况下,您将不使用panic(您应该返回error),并且在某些情况下,在测试和快速终止程序中几乎不需要os.Exit.

Most of the time you won't use panic (you should return an error instead), and you almost never need os.Exit outside of some cases in tests and for quick program termination.

这篇关于何时使用os.Exit()和panic()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆