re-raising an exception with the original backtrace

J

Joel VanderWerf

Is there a way to re-raise an exception without replacing its backtrace
with the current one?

The reason I want to do this is that I am catching an exception and
passing it to a handler. The handler needs to make a decision and then,
possibly, re-raise the same exception, preferrably with the same
information as it originally contained.

But if I do the following, the exception takes on the backtrace of the
handler, which has lost some information. I know I can add the original
backtrace to the exception's message, but that's not the same thing...

$ cat exception.rb

class MyError < StandardError; end

def foo
raise MyError
end

def main
foo
rescue Exception => e
handler(e)
end

def handler(e)
ok = false
if ok
return true
else
puts "backtrace:", e.backtrace, "---"
raise e
end
end

main

$ ruby exception.rb
backtrace:
exception.rb:4:in `foo'
exception.rb:8:in `main'
exception.rb:23
---
exception.rb:19:in `handler': MyError (MyError)
from exception.rb:10:in `main'
from exception.rb:23

Note that the backtrace of e knows about foo, but the re-raised
exception does not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top