» Ruby's Favorite Exception
Ruby uses RuntimeError
a lot, so much so that it's the default exception class when calling raise
without an Exception
class:
raise "creature is too angry"
is equivalent to:
raise RuntimeError, "creature is too angry"
and raises the exception:
RuntimeError: creature is too angry
It's common to use the simpler form of raise
when you don't really care about the exception class and just want to stop the program from continuing. For example, you could use a simple raise
to guard the input to a method:
def rawr(creature)
raise "this creature can't rawr :(" unless creature.respond_to?(:rawr)
creature.rawr
end
Without the guard, accidentally calling rawr
with nil
would raise a NoMethodError
:
rawr(nil) # => NoMethodError: undefined method `rawr' for nil:NilClass
With the guard, we get a more helpful exception:
rawr(nil) # => RuntimeError: this creature can't rawr :(
Of course, RuntimeError
can also be overused. Because it inherits directly from StandardError
, you must go pretty broad to rescue RuntimeError
, which isn't usually a good idea. If you are building an API that will be used by others, it's a good idea to raise your own exception classes.
Fun fact: Prior to version 2.5, Ruby raised RuntimeError
when attempting to modify a frozen object. Ruby 2.5 introduced FrozenError
, a more specific error class.