Implied types in Ruby's rescue clause

Posted by collin
on Tuesday, July 29

There are two different ways in which you’ll see people using rescue in Ruby:

begin
  # do something terrible
rescue
  # handle error in $!
end

And the more explicit way:

begin
  # do something terrible
rescue StandardError => e
  # handle error using e
end

These two are actually equivalent, as the former, shorter version implies that you are catching any error that is or is a subclass of StandardError. The problem is that while StandardError does encompass a large number of different exception types, it still lives under the broader umbrella of Exception:

% cheat exceptions
exceptions:
  Exception
   NoMemoryError
   ScriptError
     LoadError
     NotImplementedError
     SyntaxError
   SignalException
     Interrupt
   StandardError
     ArgumentError
     IOError
       EOFError
     IndexError
     LocalJumpError
     NameError
       NoMethodError
     RangeError
       FloatDomainError
     RegexpError
     RuntimeError
     SecurityError
     SystemCallError
     SystemStackError
     ThreadError
     TypeError
     ZeroDivisionError
   SystemExit
   fatal

The more aggressive way to rescue from error conditions is, then, to:

begin
  # the most terrible code
rescue Exception => e
  # whew
end
Comments

Leave a response