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

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.

Leave a Comment