Exception Handling (Ruby)
Ruby handles errors with begin/rescue/ensure blocks. You raise exceptions with raise and catch them with rescue, optionally cleaning up in ensure regardless of success or failure.
Ruby
Code that might fail goes in a begin block; rescue catches exceptions of a given class (and its subclasses). You can rescue specific types (rescue ArgumentError => e), and a bare rescue catches StandardError. Raise an error with raise SomeError, "message". The ensure clause always runs, ideal for closing files or releasing resources.
All exceptions descend from Exception, but you should rescue StandardError or its subclasses, not Exception itself, so you don't accidentally swallow signals like Interrupt. Define custom errors by subclassing StandardError to give your app meaningful, catchable error types.
Method bodies have an implicit begin, so you can write rescue directly in a method without begin. retry re-runs the begin block (handy for transient failures), and else runs only when no exception was raised.
Syntax
begin
risky
rescue SomeError => e
handle(e)
ensure
cleanup
endExamples
Ruby
def safe_divide(a, b)
a / b
rescue ZeroDivisionError => e
"error: #{e.message}"
end
puts safe_divide(10, 2)
puts safe_divide(10, 0)Output:
5
error: divided by 0