SystemExit 是一种特殊的异常吗?
SystemExit
的行为与其他 Exception
有何不同?我想我理解为什么提出适当的异常不好的一些原因。例如,您不希望发生这样的奇怪事情:
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
但是如何救援会忽略SystemExit
? (它使用什么标准?)
How does SystemExit
behave differently from other Exception
s? I think I understand some of the reasoning about why it wouldn't be good to raise a proper Exception. For example, you wouldn't want something strange like this to happen:
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
But how does the rescue
ignore SystemExit
? (What criteria does it use?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您编写没有一个或多个类的
rescue
时,它与编写相同:但是,有些异常不是从
StandardError
继承的。SystemExit
是其中之一,因此不会捕获它。以下是 Ruby 1.9.2 中层次结构的子集,您可以自己查找< /a>:因此,您可以使用以下方式捕获仅
SystemExit
:...或者您可以选择捕获每个异常,包括
SystemExit
with:自己尝试一下:
请注意,此示例在(某些版本的?)IRB 中不起作用,IRB 提供了自己的退出方法来屏蔽正常的 Object#exit。
在 1.8.7 中:
在 1.9.3 中:
When you write
rescue
without one or more classes, it is the same as writing:There are Exceptions that do not inherit from
StandardError
, however.SystemExit
is one of these, and so it is not captured. Here is a subset of the hierarchy in Ruby 1.9.2, which you can find out yourself:You can thus capture just
SystemExit
with:...or you can choose to capture every exception, including
SystemExit
with:Try it yourself:
Note that this example will not work in (some versions of?) IRB, which supplies its own exit method that masks the normal Object#exit.
In 1.8.7:
In 1.9.3:
简单示例:
退出
status
/success?
等也可以读取:方法的完整列表:
[:status, :success?, :exception, :消息,:backtrace,:backtrace_locations,:set_backtrace,:原因]
Simple example:
The exit
status
/success?
, etc. can be read too:Full list of methods:
[:status, :success?, :exception, :message, :backtrace, :backtrace_locations, :set_backtrace, :cause]