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:
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.
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:
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.
Designed by sketchbooks.co.kr / sketchbook5 board skin