Basic Error Handling
Prerequisites: Methods
When something goes wrong while a program runs — dividing by zero,
converting "abc" to a number — Ruby raises an exception. If
nothing handles it, the program stops and prints the error.
Real-world analogy: an exception is a fire alarm. rescue is the
plan for what to do when it goes off, instead of everyone panicking.
Syntax
begin
# code that might fail
rescue SomeError => e
# what to do if it does
end
Example
def safe_divide(a, b)
a / b
rescue ZeroDivisionError
puts "You can't divide by zero."
nil
end
p safe_divide(10, 2)
p safe_divide(10, 0)
Expected output
5
You can't divide by zero.
nil
Inside a method, you can put rescue directly before the method's
end — no begin needed.
Using the error
=> e stores the exception in a variable, so you can read its message:
input = "abc"
begin
number = Integer(input)
puts "You entered #{number}"
rescue ArgumentError => e
puts "Invalid number: #{e.message}"
end
Invalid number: invalid value for Integer(): "abc"
Common built-in errors you'll meet: ArgumentError (bad argument),
TypeError (wrong type), NoMethodError (method doesn't exist —
often called on nil), ZeroDivisionError, and KeyError (from
fetch).
Level 2 covers exceptions in depth: ensure, retry, raising your own
errors, and custom error classes.
Common mistakes
- Rescuing everything with a bare
rescueand hiding real bugs. Always name the specific error you expect. - Using exceptions for normal decisions. If you can check first
(
b.zero?), that's usually clearer.
Practice
Write a method parse_age(text) that returns the age as an integer,
or prints Please enter a whole number and returns nil if the text
isn't a valid integer.
Show solution
def parse_age(text)
Integer(text)
rescue ArgumentError
puts "Please enter a whole number"
nil
end
p parse_age("42")
p parse_age("forty")
42
Please enter a whole number
nil