begin / rescue / ensure
In this page:
begin / rescue / ensure
begin ... rescue ExceptionType => e ... ensure ... end is Ruby's exception handling block: begin contains risky code, rescue handles a specific exception type (or any exception if unspecified), and ensure always runs afterward regardless of whether an error occurred. This mirrors try/catch/finally in other languages, but uses different keyword names. Methods can also use an implicit begin/rescue without the explicit begin keyword.
Note: A method definition itself can have rescue/ensure clauses directly, without wrapping the whole body in an explicit begin block.
Example: begin / rescue / ensure
begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Caught: #{e.message}"
ensure
puts "Cleanup always runs"
end
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: