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
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.
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.
This means, Exception
will catch exception
for any classes below hierarchy.
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
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox