

Error Handling in Ruby: Part II
In this article, we’re going to explore the following topics:
- the
retrykeyword - 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
ivariable is set to1 - the
retry #1is printed - a
RuntimeErroris raised - the
rescueclause catches the freshly raisedRuntimeError - the
retrykeyword 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 the Kernel#raise method call gets a class that is not an Exception as argument.
Voilà !
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this article if it has been useful for you. 🚀
Here is a link to my last article: Error Handling in Ruby: Part I.