如何在Ruby中存在第二个异常呢? [英] How to get the reference alive to the older one, when there is a second exception in Ruby?

查看:393
本文介绍了如何在Ruby中存在第二个异常呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 开始
加注爆炸
rescue
p $!
raise你生气了
p $!
end

##< RuntimeError:explosion>
#RuntimeError:你是否疯狂
#from(irb):5:在`rescue in irb_binding'
#from(irb):1
#from / usr / bin / irb:12:在`< main>'

$! code>总是只保存当前异常对象引用。



但是有没有办法获得引用原始的异常对象(这里是爆炸),另一个异常已经被提出? < ~~~这是我的问题。



我自己尝试并达成了答案,希望现在对于所有在Smokey情况下的人来说,我的疑问更加清晰。

解决方案

当您拯救第二个异常时,您是否想要引用原始异常?如果是这样,那么你需要在救援期间捕获变量中的原始异常。这样做可以通过做:

  rescue StandardError =>其中StandardError可以是任何类型的异常或省略(在这种情况下,StandardError是默认值),$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 



例如,代码:

  begin 
提高原始异常
rescue StandardError => e
放原始异常:
放$!
put e
begin
raisesecond exception
rescue
putsSecond Exception:
puts $!
put e
end
end

给出输出: / p>

 原始异常:
原始异常
原始异常
第二例外:
秒例外
原始异常

正如你可以看到 e 已经存储了第二个异常之后使用的原始异常。


begin
  raise "explosion"
rescue
  p $!
  raise "Are you mad"
  p $!
end

# #<RuntimeError: explosion>
# RuntimeError: Are you mad
#    from (irb):5:in `rescue in irb_binding'
#    from (irb):1
#    from /usr/bin/irb:12:in `<main>'

$! always holds only the current exception object reference.

But is there any way to get a reference to the original exception object (here it is "explosion"), after another exception has been raised? <~~~ Here is my question.

Myself tried and reached to the answer,hope now it is more clearer to all who was in Smokey situation with my queries.

解决方案

Are you saying you want to have reference to the original exception when you rescue the second exception? If so, then you need to capture the original exception in a variable during the rescue. This is done by doing:

rescue StandardError => e

where StandardError can be any type of exception or omitted (in which case StandardError is the default).

For example, the code:

begin
    raise "original exception"
rescue StandardError => e
    puts "Original Exception:"
    puts $!
    puts e
    begin
        raise "second exception"
    rescue
        puts "Second Exception:"
        puts $!
        puts e      
    end
end

Gives the output:

Original Exception:
original exception
original exception
Second Exception:
second exception
original exception

As you can see e has stored the original exception for use after the second exception.

这篇关于如何在Ruby中存在第二个异常呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆