Bird
Raised Fist0
Rubyprogramming~10 mins

Why error handling uses rescue in Ruby - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why error handling uses rescue
Start program
↓
Execute code block
↓
Error occurs?
No→Continue normal flow
Yes↓
rescue catches error
↓
Handle error gracefully
↓
Continue or exit program
The program tries to run code. If an error happens, rescue catches it to handle it safely, so the program doesn't crash.
Execution Sample
Ruby
begin
  puts 10 / 0
rescue ZeroDivisionError
  puts "Can't divide by zero!"
end
This code tries to divide 10 by 0, which causes an error. rescue catches the error and prints a message instead of crashing.
Execution Table
StepActionEvaluationResult
1Execute puts 10 / 010 / 0Error: ZeroDivisionError raised
2rescue ZeroDivisionError catches errorError matches ZeroDivisionErrorControl moves to rescue block
3Execute puts "Can't divide by zero!"Print messageOutput: Can't divide by zero!
4End of begin-rescue blockNo more codeProgram continues safely
💡 Error is caught by rescue, so program does not crash and continues.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
ErrorNoneZeroDivisionError raisedCaught by rescueHandled
Key Moments - 3 Insights
Why doesn't the program crash when dividing by zero?
Because the rescue block catches the ZeroDivisionError at step 2 in the execution table, preventing a crash.
What happens if the error is not the one specified in rescue?
The error would not be caught and the program would crash, since rescue only handles specified errors (see step 2).
Does the code after rescue run if no error occurs?
No error means rescue block is skipped and program continues normal flow (not shown in this example).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 2?
AThe division is performed successfully
BThe program crashes
CThe error is caught by rescue
DThe program skips the rescue block
💡 Hint
Check the 'Action' and 'Result' columns at step 2 in the execution table.
At which step does the program print the message "Can't divide by zero!"?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column for printing output in the execution table.
If the rescue block was missing, what would happen at step 2?
AThe error would be caught anyway
BThe program would crash due to unhandled error
CThe program would print the message anyway
DThe program would skip the error
💡 Hint
Refer to the explanation in key moments about what happens if error is not rescued.
Concept Snapshot
Use begin...rescue to handle errors in Ruby.
If an error happens in begin block, rescue catches it.
This prevents program crash and allows graceful handling.
Specify error type after rescue to catch specific errors.
Without rescue, errors stop the program immediately.
Full Transcript
This example shows how Ruby uses rescue to handle errors. The program tries to divide 10 by zero, which causes a ZeroDivisionError. Instead of crashing, the rescue block catches this error and prints a friendly message. This way, the program continues safely. Rescue only catches errors specified after it, so other errors will still crash the program if not handled. Using rescue helps keep programs running smoothly even when unexpected problems happen.

Practice

(1/5)
1. Why do Ruby programs use rescue in error handling?
easy
A. To make the code shorter
B. To speed up the program execution
C. To catch errors and prevent the program from crashing
D. To automatically fix all errors

Solution

  1. Step 1: Understand the purpose of rescue

    rescue is used to catch errors that happen during program execution.
  2. Step 2: Recognize the benefit of catching errors

    Catching errors prevents the program from crashing and allows it to handle problems gracefully.
  3. Final Answer:

    To catch errors and prevent the program from crashing -> Option C
  4. Quick Check:

    rescue catches errors = C [OK]
Hint: Remember: rescue stops crashes by catching errors [OK]
Common Mistakes:
  • Thinking rescue speeds up code
  • Believing rescue fixes errors automatically
  • Confusing rescue with code shortening
2. Which of the following is the correct syntax to handle errors using rescue in Ruby?
easy
A. error do # handle error end
B. try # code catch # error handling end
C. if error # handle error end
D. begin # code rescue # error handling end

Solution

  1. Step 1: Identify Ruby's error handling syntax

    Ruby uses begin and rescue blocks to handle errors.
  2. Step 2: Compare options to Ruby syntax

    begin # code rescue # error handling end matches Ruby's syntax exactly; others use syntax from other languages or incorrect forms.
  3. Final Answer:

    begin\n # code\nrescue\n # error handling\nend -> Option D
  4. Quick Check:

    Ruby uses begin-rescue-end = D [OK]
Hint: Remember Ruby uses begin and rescue keywords [OK]
Common Mistakes:
  • Using try-catch like other languages
  • Using if statements for error handling
  • Misplacing rescue outside begin-end
3. What will be the output of this Ruby code?
begin
  puts 10 / 0
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
end
medium
A. 0
B. Cannot divide by zero!
C. Infinity
D. Error: division by zero

Solution

  1. Step 1: Identify the error raised

    Dividing 10 by 0 raises a ZeroDivisionError in Ruby.
  2. Step 2: Check the rescue block handling

    The rescue block catches ZeroDivisionError and prints "Cannot divide by zero!".
  3. Final Answer:

    Cannot divide by zero! -> Option B
  4. Quick Check:

    ZeroDivisionError caught prints message = A [OK]
Hint: Look for error type matched in rescue block [OK]
Common Mistakes:
  • Expecting program to crash with error message
  • Thinking division by zero returns 0 or Infinity
  • Ignoring rescue block effect
4. Find the error in this Ruby code snippet:
begin
  puts 5 + '3'
rescue
  puts "Error caught!"
end
medium
A. Adding integer and string causes a TypeError
B. The rescue block is missing the error type
C. The begin keyword is not needed
D. The puts statement is incorrect

Solution

  1. Step 1: Analyze the operation inside begin block

    Adding 5 (integer) and '3' (string) causes a TypeError in Ruby.
  2. Step 2: Understand rescue block behavior

    The rescue block catches the error and prints "Error caught!"; the error is due to incompatible types.
  3. Final Answer:

    Adding integer and string causes a TypeError -> Option A
  4. Quick Check:

    TypeError from adding int and string = A [OK]
Hint: Check data types when rescue catches errors [OK]
Common Mistakes:
  • Thinking rescue must specify error type
  • Believing begin is optional here
  • Assuming puts causes error
5. You want to handle different errors separately in Ruby. Which code correctly uses rescue to handle ZeroDivisionError and NoMethodError differently?
begin
  # some code
rescue ZeroDivisionError
  puts "Divide by zero error"
rescue NoMethodError
  puts "Method not found error"
end
hard
A. This code correctly handles each error with separate rescue blocks
B. You cannot have multiple rescue blocks; only one is allowed
C. You must use if statements inside rescue to check error type
D. Rescue only catches StandardError, so this won't work

Solution

  1. Step 1: Understand multiple rescue usage

    Ruby allows multiple rescue clauses to handle different error types separately.
  2. Step 2: Verify code matches correct syntax

    The code uses separate rescue blocks for ZeroDivisionError and NoMethodError, which is valid.
  3. Final Answer:

    This code correctly handles each error with separate rescue blocks -> Option A
  4. Quick Check:

    Multiple rescue blocks handle errors separately = B [OK]
Hint: Use multiple rescue blocks for different errors [OK]
Common Mistakes:
  • Thinking only one rescue block is allowed
  • Trying to use if inside rescue instead
  • Believing rescue can't catch specific errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard