The stack trace is precious!
The stack trace is one of the most valuable pieces of information you can have when trying to debug a problem. It tells you what line of code was being run when an error was thrown and gives you an idea of the execution path that lead to that line of code being run.
Quick plea then. Please don't do this:
def foo
do_something
rescue => e
puts "Problem: #{e}"
raise e
end
This will start a new stack trace at raise e. If I rescue this further up the stack there's no indication of where the problem was originally encountered - I just get pointed at your error handling code. Precious information, gone.
Do this instead:
def foo
do_something
rescue => e
puts "Problem: #{e}"
raise
end
Note the lack of argument in the call to raise. This tells Ruby to re-raise the last exception. The stack trace remains intact and debugging can continue unhindered. Glory be!
Leave feedback...
Commenting is closed for this article.

Ha! No wonder Ruby felt so familiar! c# has the exact same issue, so you have to trawl thru the e.InnerException etc.
But hey, it’s better than
;-)
I wish Java had that feature. In java, the usual patter is:
throw new Exception(“message”, originalException).You get the original stacktrace, but must wade through many-many lines of “rethrows”.
All this time I’ve been doing it wrong. Thanks for showing me the true way to re-raise an exception!
Thanks for posting this! I’m pretty familiar with Ruby’s exception handling, but I did not know this exceptionally useful tip.