Recall & Review
beginner
What is the purpose of multiple rescue clauses in Ruby?
Multiple rescue clauses allow you to handle different types of errors separately, giving specific responses for each error type.
Click to reveal answer
beginner
How do you write multiple rescue clauses in Ruby?
You write multiple rescue clauses by listing different rescue blocks one after another, each specifying a different error class to catch.Click to reveal answer
intermediate
What happens if an exception does not match any rescue clause?
If an exception does not match any rescue clause, it will propagate up the call stack and may cause the program to terminate if not handled elsewhere.
Click to reveal answer
beginner
Example: What will this code output?
begin 1 / 0 rescue ZeroDivisionError puts 'Cannot divide by zero' rescue StandardError puts 'Some other error' end
The output will be: Cannot divide by zero
Because the error is ZeroDivisionError, the first rescue clause handles it.
Click to reveal answer
intermediate
Can you rescue multiple exceptions in a single rescue clause?
Yes, you can rescue multiple exceptions by listing them separated by commas after rescue, like: rescue IOError, EOFError.
Click to reveal answer
What keyword is used to handle exceptions in Ruby?
✗ Incorrect
In Ruby, the keyword 'rescue' is used to handle exceptions.
If you want to handle both IOError and EOFError in the same rescue clause, how do you write it?
✗ Incorrect
You list multiple exceptions separated by commas after rescue: rescue IOError, EOFError.
What happens if an exception is not rescued in any rescue clause?
✗ Incorrect
If an exception is not rescued, it propagates up and may crash the program.
Which rescue clause will handle a ZeroDivisionError if multiple rescue clauses exist?
✗ Incorrect
Ruby executes the first rescue clause that matches the exception type.
Can you have an else clause after multiple rescue clauses?
✗ Incorrect
The else clause runs only if no exceptions are raised in the begin block.
Explain how multiple rescue clauses work in Ruby and why they are useful.
Think about catching different problems separately.
You got /3 concepts.
Write a Ruby code snippet that rescues both ZeroDivisionError and TypeError with different messages.
Use separate rescue clauses for each error.
You got /3 concepts.