加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:19:54 所属栏目:百科 来源:网络整理
导读:SystemExit与其他异常的行为有何不同?我认为我理解了为什么提出适当的例外不太好的一些推理.例如,你不会想要这样的奇怪的事情发生: begin exitrescue = e # Silently swallow up the exception and don't exitend 但是如何抢救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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读