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
it will throw an exception with class
Catching exception wit Exception class
Now, if we try to catch exception
raised for the example above with
it will be done as follows.
As we can see, it caught the exception correctly.
Exception class is designed to catch exceptions
all descendant class exceptions.
To understand this, Exception hierarchy in Ruby is given below.
Exception will catch exception
for any classes below hierarchy.
As we can see, the example above catches
1.....5 is not a valid syntax of Ruby.
We might not want to catch this exception.
But it was catched
we had mentioned
Exception class for
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.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox