Error Handling in Ruby: Part II
In this article, we’re going to explore the following topics:
- the
retry
keyword - custom errors
Feel free to have a look to Error Handling in Ruby: Part I article.
The retry keyword
The retry
keyword re-executes the code contained in the begin...end
block
produces
retry #1
retry #2
retry #3
Let’s detail the execution flow of this piece of code:
- the
i
variable is set to1
- the
retry #1
is printed - a
RuntimeError
is raised - the
rescue
clause catches the freshly raisedRuntimeError
- the
retry
keyword is invoked becausei < 3
The retry
keyword re-executes the code within the begin...end
block until i=3
.
Note that the begin...rescue...end
clause can access variables of the calling scope.
The retry
keyword can only be called within a rescue
block. Otherwise, a SyntaxtError
is raised
irb> retry
SyntaxError: Invalid retry
Custom errors
An error is an instance of a class that includes the Exception
class in its ancestor chain.
NB: feel free to have a look to the Ruby Object Model: Part I article if you’re unfamiliar with the
ancestor chain
in Ruby.
So, we can create a new error type by simply declaring a new class that inherit from a class that includes the Exception
class in its ancestor chain
produces
PolicyError: access not granted
UserPolicyError: user unauthorized
Here, the PolicyError
class directly inherit from Exception
when the UserPolicyError
inherits from the PolicyError
class.
Now, let’s try to raise a class that doesn’t include the Exception
class in its ancestor chain
produces
TypeError (exception class/object expected)
A TypeError
is raised if raise
gets a class that is not an Exception
as argument.
Voilà !
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚