0
0
Rubyprogramming~10 mins

Begin/rescue/end blocks in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Begin/rescue/end blocks
Start begin block
Execute code inside begin
Error?
NoEnd begin block
Yes
Enter rescue block
Handle error
End begin block
The program tries code inside begin. If an error happens, it jumps to rescue to handle it, then ends the block.
Execution Sample
Ruby
begin
  puts 10 / x
rescue ZeroDivisionError
  puts "Cannot divide by zero"
end
Tries to divide 10 by x; if x is zero, rescue prints a message instead of crashing.
Execution Table
StepActionCode LineResultOutput
1Start begin blockbeginBegin block started
2Execute divisionputs 10 / xError: undefined local variable or method `x'
3Error caughtrescue ZeroDivisionErrorNo ZeroDivisionError, but NameError raised
4Unhandled errorendProgram crashes with NameError
💡 Execution stops due to unhandled NameError because x is not defined
Variable Tracker
VariableStartAfter Step 2Final
xundefinedundefinedundefined
Key Moments - 2 Insights
Why does the rescue block not catch the error in step 2?
Because the error is NameError (undefined variable), but rescue only catches ZeroDivisionError as shown in execution_table row 3.
What happens if the error matches the rescue type?
The program jumps to the rescue block to run its code, then continues after end, preventing a crash.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what error occurs at step 2?
ANo error
BZeroDivisionError
CNameError
DSyntaxError
💡 Hint
Check the 'Result' column in step 2 of the execution_table
At which step does the program crash due to unhandled error?
AStep 4
BStep 1
CStep 3
DStep 2
💡 Hint
Look at the 'Result' column for step 4 in execution_table
If x was zero, which step would rescue handle the error?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Rescue handles ZeroDivisionError as shown in step 3 of execution_table
Concept Snapshot
begin
  # code that might fail
rescue ErrorType
  # code to handle error
end

- begin runs code
- rescue catches errors of given type
- end closes block
- prevents program crash by handling errors
Full Transcript
This example shows how Ruby's begin/rescue/end blocks work. The program tries to run code inside begin. If an error happens, it looks for a matching rescue block to handle it. If the error matches, rescue runs its code to fix or report the problem, then the program continues safely. If no rescue matches, the program crashes. In the example, dividing by x causes an error. Since x is not defined, a NameError happens, but rescue only catches ZeroDivisionError, so the program crashes. If x was zero, rescue would catch the division error and print a message instead of crashing.