Exceptions
Ruby has genuine structured exception-handling syntax: begin wraps code that might fail, rescue catches a specific exception class (and can bind it to a variable with =>), and ensure runs unconditionally afterward, whether or not anything was raised — useful for cleanup. This is a real language feature with its own keywords, unlike Perl's die/eval/$@ approach covered in Perl's own course.
def divide(a, b)
begin
a / b
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
nil
ensure
puts "divide(#{a}, #{b}) attempted"
end
end
puts divide(10, 2)
puts divide(10, 0)
divide(10, 2) attempted 5 Error: divided by 0 divide(10, 0) attempted
Look closely at the ordering: for divide(10, 2), ensure's "divide(10, 2) attempted" prints before the outer puts gets a chance to print 5 — ensure always runs as the method returns, before that return value reaches whoever called it. For divide(10, 0), rescue's message prints first, then ensure's, then the outer puts prints an empty line (nil has nothing visible to show).
raise throws your own exception, optionally with a message, and rescue can target that exact class:
def check_age(age)
raise ArgumentError, "age cannot be negative" if age < 0
age
end
begin
check_age(-5)
rescue ArgumentError => e
puts "Caught: #{e.message}"
end
Caught: age cannot be negative
raise if age < 0 reads naturally because if is a modifier here, not a block — the same if-as-expression idea from lesson 6, now used as a one-line guard clause. Next: closing thoughts — tying blocks, symbols, and mixins together.
Practice exercise
Write safe_divide(a, b) that returns a / b, rescuing ZeroDivisionError by returning nil instead. Print safe_divide(10, 2), then print safe_divide(10, 0).inspect.