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

begin / rescue / ensure

In this page:

  1. begin / rescue / ensure

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
🔒

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.