← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 3 of 6

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:

  1. begin / rescue / ensure
Syntax
ruby
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

markup
begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Caught: #{e.message}"
ensure
  puts "Cleanup always runs"
end
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
  1. Rescuing everything with rescue Exception, which also catches signals and exit; use rescue StandardError.
  2. Forgetting that ensure runs even after an error, and putting code there that should only run on success.
  3. Writing rescue with the wrong class, such as ArgumentError for a ZeroDivisionError, so the error is not caught.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.