Shameless Plug: Don’t make any exceptions. Protect your privacy online with a VPN Service when browsing the web.
p $!, *$@ is a little more optimal in that you will see the class of the exception also.
I’ll put the meat of this post first so you don’t have to waste your time if you already know this. The simplest way to catch and print out an exception along with it’s backtrace:
# 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
At some point we all want to catch an exception, print it out, and then move on to something else. I just wanted to point out a very simple way to do this. I want to point this out because I have seen many people spend far too much typing on this (myself included). Here’s a combined example of the overtyping I’ve seen used.
begin ... rescue Exception => ex puts ex.message puts ex.backtrace.join("\n") end
First off, Ruby stores the last exception caught in the special (thread local) variable
$! and the backtrace of the last exception in
$@. So there is no need to explicitly specify a variable to store it in. Secondly,
Exception#message in most cases is redundant because it’s just aliased to
puts will call for you. Thirdly calling
join("\n") is redundant when passing an array to
puts. By default
puts will output an array with a newline between each item. Also you might not have known that you can pass multiple arguments to
puts and it will be just as if you had called
puts for each one.
Usually the message of the exception is clear enough so you don’t need to see its class. But in the cases where you want to, we can easily show this too without much more work:
rescue p $! puts $@ end # or rescue puts $!.inspect, $@ end
p will call
inspect on the exception which will show it’s class and message.
I know this is simple and trivial stuff but I still see a lot of people doing it a more verbose way than necessary. Some people will probably argue that it’s less understandable my way or we should be more explicit or something and that’s a matter of opinion but I personally disagree with it. Anyway this post is mainly for the people who would like doing it the shorter way but just didn’t know about it yet.