Handling Exceptions in Ruby

Handling Exceptions in Ruby is Easy!

Exceptions are Ruby’s way of allowing us to attempt to recover from errors. The basic syntax for handling exceptions in Ruby goes something like this:

We can gather more information from an exception like so:

Notice we rescued StandardError and not Exception. There are many types of exception you might not necessarily want to rescue. For example, pressing CTRL+C or sending SIGTERM to the process would not work as expected and you might have to resort to SIGKILL.

Implicit Contexts

It’s not always necessary to explicitly type begin. Class, module, and method definitions and ruby blocks serve as implicit rescue contexts.

Rescuing exceptions is a good use case for a logger.

Multiple Exception Handling

You can handle multiple types of exception differently. Just be sure to put specific exception types before StandardError if rescue it.

Re-raising Exceptions

You can re-raise an exception after doing something with it. raise knows to re-raise the exception in the rescue context.


You can retry the error-prone task after rescuing.

Just be sure to check whether you’ve already retried first to avoid an endless loop if the fix doesn’t work.

Cleaning Up

In some situations there’s code that needs to run whether there’s an exception or not. The most common example is closing a file handle

Defining Your Own Exceptions


Use fail rather than raise to surface an exception unless you are reraising as above.

About Alexander

Alexander has been programming for a very long time. When he met Ruby, it was love at first sight.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *