Ruby catch exceptions with StandardError and not Exception

When catching exceptions in Ruby, people often tend to use Exception class. This is often not the intended class. It’s important to understand when to use StandardError, RuntimeError or any other exception class to catch exceptions.

Let’s take an example.

If we try to divide any number with 0, it will throw an exception with class ZeroDivisionError

$ 4 / 0
# Output:
# ZeroDivisionError: divided by 0

Catching exception wit Exception class

Now, if we try to catch exception raised for the example above with Exception class, it will be done as follows.

begin
  4 / 0
rescue Exception
  puts "Can't divide a number by 0"
end
# Output:
# Can't divide a number by 0

As we can see, it caught the exception correctly.

But, Exception class is designed to catch exceptions of all descendant class exceptions.

To understand this, Exception hierarchy in Ruby is given below.

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

This means, Exception will catch exception for any classes below hierarchy.

begin
 1.....5
 puts 'some syntax error on above line by mistake'
rescue Exception
  puts 'caught the exception, do I want to?'
end

As we can see, the example above catches as exception SyntaxError, as 1.....5 is not a valid syntax of Ruby.

We might not want to catch this exception. But it was catched as we had mentioned Exception class for rescue operation.

Conclusion

Well, the title of post doesn’t define a global standard. It really depends on what kind of exception(s) we want to catch and use the exception class(es) accordingly.

References

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee