当你写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,它提供了自己的退出方法来屏蔽正常的 Object#exit。
在 1.8.7 中:
method :exit
#=> #<Method: Object(IRB::ExtendCommandBundle)#exit>
在 1.9.3 中:
method :exit
#=> #<Method: main.irb_exit>