Ruby exception handling
This course covers exception handling in Ruby. It starts with raise and the exception object, an instance of a class with its own class and message. It then covers begin and rescue for catching a specific class, the order of several rescue clauses, and the bare rescue boundary at StandardError. Later lessons explain else and ensure, custom exception classes and hierarchies, and rescuing Rails exceptions such as ActiveRecord::RecordNotFound and ActiveRecord::RecordInvalid by name. A final method combines every piece.
What you'll learn
- ✓How raise stops execution and unwinds through calling methods
- ✓Catching a specific exception class with begin and rescue
- ✓Why a bare rescue stops at StandardError and skips SignalException and SystemExit
- ✓Using else for clean runs and ensure for cleanup on every path
- ✓Defining custom exception classes and hierarchies
- ✓Rescuing Rails exceptions by name and reading e.record and e.param
raise and the exception object
In an earlier course, code you wrote raised ActiveRecord::RecordNotFound or ActiveModel::ForbiddenAttributesError. The page broke, a stack trace showed up, and the fix was to change the code so the error stopped happening. This course is about what happens in that moment, and how to take control of…
Read the full lesson free →Curriculum
7 lessonsraise and the exception object
How raise stops execution and unwinds calls, and why each exception is an object with a class and message.
begin/rescue: catching a specific exception
Using begin and rescue to catch one exception class, ordering several rescue clauses, and rescuing a whole method body.
Bare rescue and the StandardError boundary
Why a bare rescue catches StandardError and its subclasses but skips SignalException, SystemExit and other siblings.
else and ensure
How else runs only after a clean begin block, and how ensure runs on every exit path.
Custom exception classes
Defining exception classes in one line, raising them with clear messages, and grouping them under a shared parent class.
Rescuing Rails' own exceptions
Rescuing RecordNotFound, RecordInvalid, ParameterMissing and ForbiddenAttributesError by name, including the extra data some of them carry.
Putting it together
A withdraw method that combines custom exceptions, specific raise calls and ensure, plus a review of the bare rescue boundary.