Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...