问题描述
如何 c c> c c c c (它使用什么标准?)
But how does the rescue ignore SystemExit? (What criteria does it use?)
推荐答案
当你写 rescue 没有一个或多个课程,作为写作:
When you write rescue without one or more classes, it is the same as writing:
begin ... rescue StandardError => e ... end
有异常不继承 StandardError 。 SystemExit 是其中之一,因此没有被捕获。这是Ruby 1.9.2中的层次结构的一个子集,您可以:
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:
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 :
You can thus capture just SystemExit with:
begin ... rescue SystemExit => e ... end
...或者您可以选择捕获每个异常,包括 SystemExit 与:
...or you can choose to capture every exception, including SystemExit with:
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中运行,IRB提供了自己的退出方法来掩盖正常的对象#退出。
Note that this example will not work in (some versions of?) IRB, which supplies its own exit method that masks the normal Object#exit.
在1.8.7中: / p>
In 1.8.7:
method :exit #=> #<Method: Object(IRB::ExtendCommandBundle)#exit>
在1.9.3中:
method :exit #=> #<Method: main.irb_exit>
这篇关于SystemExit是一种特殊的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!