Ben*_*kes 14 ruby exception-handling exit
如何SystemExit表现与其他Exceptions 不同?我想我明白了一些关于为什么它的推理不会是很好的提高适当的异常.例如,您不希望发生类似这样的奇怪事件:
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
Run Code Online (Sandbox Code Playgroud)
但怎么也该rescue忽略SystemExit?(它使用什么标准?)
Phr*_*ogz 21
begin
...
rescue StandardError => e
...
end
Run Code Online (Sandbox Code Playgroud)
但是,有些异常不会继承StandardError.SystemExit是其中之一,因此它没有被捕获.这是Ruby 1.9.2中层次结构的一个子集,您可以自己找到:
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
Run Code Online (Sandbox Code Playgroud)
因此,您可以捕获只是 SystemExit用:
begin
...
rescue SystemExit => e
...
end
Run Code Online (Sandbox Code Playgroud)
...或者您可以选择捕获每个例外,包括SystemExit:
begin
...
rescue Exception => e
...
end
Run Code Online (Sandbox Code Playgroud)
亲自尝试一下:
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..."
Run Code Online (Sandbox Code Playgroud)
请注意,此示例不适用于(某些版本的?)IRB,它提供了自己的退出方法,可以屏蔽正常的Object#exit.
在1.8.7中:
method :exit
#=> #<Method: Object(IRB::ExtendCommandBundle)#exit>
Run Code Online (Sandbox Code Playgroud)
在1.9.3中:
method :exit
#=> #<Method: main.irb_exit>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6628 次 |
| 最近记录: |