Ryan Davis’s Ruby QuickRef says (without explanation):
Don’t rescue Exception. EVER. or I will stab you.
Why not? What’s the right thing to do?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
TL;DR: Use
StandardErrorinstead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuingExceptionis probably okay.Exceptionis the root of Ruby’s exception hierarchy, so when yourescue Exceptionyou rescue from everything, including subclasses such asSyntaxError,LoadError, andInterrupt.Rescuing
Interruptprevents the user from using CTRLC to exit the program.Rescuing
SignalExceptionprevents the program from responding correctly to signals. It will be unkillable except bykill -9.Rescuing
SyntaxErrormeans thatevals that fail will do so silently.All of these can be shown by running this program, and trying to CTRLC or
killit:Rescuing from
Exceptionisn’t even the default. Doingdoes not rescue from
Exception, it rescues fromStandardError. You should generally specify something more specific than the defaultStandardError, but rescuing fromExceptionbroadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.If you have a situation where you do want to rescue from
StandardErrorand you need a variable with the exception, you can use this form:which is equivalent to:
One of the few common cases where it’s sane to rescue from
Exceptionis for logging/reporting purposes, in which case you should immediately re-raise the exception: