SystemExit是一种特殊的exception吗?
SystemExit
与其他Exception
的行为有何不同? 我想我理解为什么提出一个正确的例外是不好的一些推理。 例如,您不希望发生类似这样的奇怪事件:
begin exit rescue => e # Silently swallow up the exception and don't exit end
但rescue
如何忽略SystemExit
? (它使用什么标准?)
当你在没有一个或多个课程的情况下写rescue
, 它与写作相同 :
begin ... rescue StandardError => e ... end
但是,有些exception不会从StandardError
inheritance。 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
因此,您可以使用以下命令捕获SystemExit
:
begin ... rescue SystemExit => e ... end
…或者您可以选择捕获每个exception,包括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 #=> #
在1.9.3中:
method :exit #=> #
简单的例子:
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]