Errors for Rubys
Errors in Ruby are handled with exceptions: raise signals a problem and begin, rescue, else and ensure catch and clean up. This unit also covers reading and writing files and using the standard library, such as File, Dir, JSON, Time and Set, so scripts can work safely with the outside world.
Stage: Objects · Part of the Ruby roadmap · Last reviewed 19 November 2026
What to learn in Errors
- Rescue a specific exception class and let others pass
- Use ensure so files and connections are always closed
- Define a custom error class inherited from StandardError
- Read a file line by line using File.open with a block
- Parse and generate JSON with the standard library
Errors interview questions
Why rescue a specific exception rather than a bare rescue?
A bare rescue catches StandardError, which can hide bugs such as typos raising NoMethodError. Rescuing a named class handles only the failure you expect and lets unexpected errors surface. Rescuing Exception is worse, since it also catches system exit signals.
Why pass a block to File.open?
With a block, Ruby closes the file automatically when the block ends, even if an exception is raised. Without it you must call close yourself, and forgetting can leak file handles or leave data unflushed.
Where Errors fits in the Ruby roadmap
Errors belongs to the Objects stage (beginner level), which takes about 17 hours. Object-oriented Ruby.