Friday, February 13, 2009

Printing exceptions in Ruby

Steve wrote a post about the simplest way to print an exception's message and backtrace in ruby.

The snippet he provides is the following:

# catch most exceptions (anything that derives from StandardError)
begin
...
rescue
puts $!, $@
end

# catch all exceptions (anything that derives from Exception)
begin
...
rescue Exception
puts $!, $@
end
end


The $! variable contains the last exception and $@ contains the last exception's backtrace as a string.

Some people (including me, before reading his post) do the following:

begin
...
rescue Exception => ex
puts ex.message
puts ex.backtrace.join("\n")
end


I'm glad I stumbled upon Steve's post. Learning about the little idioms of a language helps you to write more succinct and clear code.

No comments:

Post a Comment