Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 25 / 68

Writing a Custom Exception Class

In this lesson you will learn how to define a custom exception class in Ruby so error types are easy to tell apart. This is for anyone searching for "Ruby custom exception how to create".

Inheriting from StandardError gives you an exception of your own. Naming a class per kind of failure makes it much easier to tell what went wrong when you rescue it.

The sample code creates a custom exception with the single-line definition class ValidationError < StandardError; end. It raises it inside check_age with raise ValidationError, "..." when the age is invalid, and catches it with rescue ValidationError => e.

A common stumbling block for beginners is the variety of ways to write raise. Separating the class name and the message with a comma, as in raise ClassName, message, takes a moment to get used to.

Giving an exception a cause lets it carry the details of the original underlying failure along with it. The larger the application, the more this kind of custom exception design matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)