begin / rescue / ensure
begin, rescue, and ensure make a safety net: try something risky, rescue the problem if it falls, and ensure cleanup always happens. It keeps the program from crashing.
In this page:
Syntax
begin
# code that may fail
rescue ExceptionType => e
# handle e.message
ensure
# always runs
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Rescuing everything with
rescue Exception, which also catches signals and exit; userescue StandardError. - Forgetting that
ensureruns even after an error, and putting code there that should only run on success. - Writing
rescuewith the wrong class, such asArgumentErrorfor aZeroDivisionError, so the error is not caught.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: