3 systemexit 报错_SystemExit是一种特殊的异常?

bd96500e110b49cbb3cd949968f18be7.png

How does SystemExit behave differently from other Exceptions? I think I understand some of the reasoning about why it wouldn't be good to raise a proper Exception. For example, you wouldn't want something strange like this to happen:

begin

exit

rescue => e

# Silently swallow up the exception and don't exit

end

But how does the rescue ignore SystemExit? (What criteria does it use?)

解决方案

When you write rescue without one or more classes, it is the same as writing:

begin

...

rescue StandardError => e

...

end

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

You can thus capture just SystemExit with:

begin

...

rescue SystemExit => e

...

end

...or you can choose to capture every exception, including SystemExit with:

begin

...

rescue Exception => e

...

end

Try it yourself:

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..."

Note that this example will not work in (some versions of?) IRB, which supplies its own exit method that masks the normal Object#exit.

In 1.8.7:

method :exit

#=> #

In 1.9.3:

method :exit

#=> #

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值