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...

  1. 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

    def foo
      do_something
    rescue => e
      puts “oops!”
    end

    ;-)

  2. 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”.

  3. All this time I’ve been doing it wrong. Thanks for showing me the true way to re-raise an exception!

  4. Thanks for posting this! I’m pretty familiar with Ruby’s exception handling, but I did not know this exceptionally useful tip.

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.