In this article, we’re going to explore the following topics:

the retry keyword

keyword custom errors

Feel free to have a look to Error Handling in Ruby: Part I article.

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

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 to 1

variable is set to the retry #1 is printed

is printed a RuntimeError is raised

is raised the rescue clause catches the freshly raised RuntimeError

clause catches the freshly raised the retry keyword is invoked because i < 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à !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com