The Stack Trace Is Precious

November 10, 2009

The stack trace is one of the most valuable pieces of information you can have when debugging. It tells you exactly which line of code was running when an error was thrown, and it gives you the full execution path that led there.

So here is a quick plea. Please don't do this:

def foo
  do_something
rescue => e
  puts "Problem: #{e}"
  raise e
end

Writing raise e starts a new stack trace originating at the raise call itself. If something further up the stack rescues this exception, there is no indication of where the problem originally occurred — all you get is a pointer to the error handling code. Precious information, gone.

Do this instead:

def foo
  do_something
rescue => e
  puts "Problem: #{e}"
  raise
end

Notice the bare raise with no argument. This tells Ruby to re-raise the current exception, keeping the original stack trace intact. Debugging can continue unhindered.

Questions or thoughts? Get in touch.