Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

How to get the reference alive to the older one, when there is a second exception in Ruby?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...