SystemExit
与其他Exception
s有什么不同?我想我明白一些关于为什么不会很好地提出适当的例外的一些推理。例如,你不会想一些奇怪的事情是这样发生的:SystemExit是一种特殊的异常吗?
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
但请问该怎么rescue
忽略SystemExit
? (它使用什么样的标准?)
SystemExit
与其他Exception
s有什么不同?我想我明白一些关于为什么不会很好地提出适当的例外的一些推理。例如,你不会想一些奇怪的事情是这样发生的:SystemExit是一种特殊的异常吗?
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
但请问该怎么rescue
忽略SystemExit
? (它使用什么样的标准?)
当你写rescue
没有一个或多个类,it is the same写作:
begin
...
rescue StandardError => e
...
end
有不从StandardError
继承例外,但是。 SystemExit
就是其中之一,所以没有被捕获。下面是层次结构中的Ruby 1.9.2,一个子集,你可以find out yourself:
BasicObject
Exception
NoMemoryError
ScriptError
LoadError
Gem::LoadError
NotImplementedError
SyntaxError
SecurityError
SignalException
Interrupt
StandardError
ArgumentError
EncodingError
Encoding::CompatibilityError
Encoding::ConverterNotFoundError
Encoding::InvalidByteSequenceError
Encoding::UndefinedConversionError
FiberError
IOError
EOFError
IndexError
KeyError
StopIteration
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError
SystemCallError
ThreadError
TypeError
ZeroDivisionError
SystemExit
SystemStackError
fatal
你可以这样捕获只是SystemExit
有:
begin
...
rescue SystemExit => e
...
end
...或者你可以选择捕捉每例外,包括SystemExit
有:
begin
...
rescue Exception => e
...
end
亲自试一试:
begin
exit 42
puts "No no no!"
rescue Exception => e
puts "Nice try, buddy."
end
puts "And on we run..."
#=> "Nice try, buddy."
#=> "And on we run..."
注意这个例子是行不通的IRB,它提供了自己的退出方法掩盖了正常的对象#出口(某些版本?)。
在1.8.7:
method :exit
#=> #<Method: Object(IRB::ExtendCommandBundle)#exit>
在1.9.3:
method :exit
#=> #<Method: main.irb_exit>
感谢您的信息。我知道你可以自己捕获'SystemExit',但我不知道没有指定一个异常类只会导致'StandardError'异常被解救。似乎解释它 - 谢谢! – 2011-02-25 20:06:18
这对于测试是否存在某些东西非常棒 – 2013-04-29 17:40:48
简单的例子:
begin
exit
puts "never get here"
rescue SystemExit
puts "rescued a SystemExit exception"
end
puts "after begin block"
出口status
/success?
等可读取太:
begin
exit 1
rescue SystemExit => e
puts "Success? #{e.success?}" # Success? false
end
begin
exit
rescue SystemExit => e
puts "Success? #{e.success?}" # Success? true
end
方法全部列表:[:status, :success?, :exception, :message, :backtrace, :backtrace_locations, :set_backtrace, :cause]
这必须是重复的。 – 2011-02-27 22:36:11
@AndrewGrimm它肯定是一个来自邮件列表和IRC的FAQ,但我似乎无法完全在S/O上找到这个问题。我发现最近的是_ [“你在Ruby中没有指定异常类时会捕获哪些异常”](http://stackoverflow.com/questions/2748515/which-exceptions-do-you-catch-when -you-dont-specified-an-exception-class-in-ruby)_,但它有点重复,不是重复的问题。 – Phrogz 2011-02-28 15:52:59
@Andrew我以为别人也必须要求同样的事情,但我没有找到任何明确回答'SystemExit'如何处理的东西。 @Phrogz感谢您的相关链接Q. – 2011-03-01 15:02:58