红宝石 – SystemExit是一种特殊的异常?

SystemExit与其他异常的行为有何不同?我认为我理解了为什么提出适当的例外不太好的一些推理.例如,你不会想要这样的奇怪的事情发生:
begin
  exit
rescue => e
  # Silently swallow up the exception and don't exit
end

但是如何抢救SystemExit呢? (它使用什么标准?)

解决方法

当你写一个没有一个或多个课程的救援,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>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...