0
0
Rubyprogramming~5 mins

Multiple rescue clauses in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Atry
Bcatch
Crescue
Dexcept
If you want to handle both IOError and EOFError in the same rescue clause, how do you write it?
Arescue IOError | EOFError
Brescue IOError, EOFError
Crescue (IOError, EOFError)
Drescue IOError && EOFError
What happens if an exception is not rescued in any rescue clause?
AThe program crashes or the exception propagates up
BThe exception is ignored silently
CThe program restarts automatically
DThe exception is converted to a warning
Which rescue clause will handle a ZeroDivisionError if multiple rescue clauses exist?
AThe first rescue clause that matches ZeroDivisionError
BThe last rescue clause
CAll rescue clauses
DNone, ZeroDivisionError is not rescued
Can you have an else clause after multiple rescue clauses?
ANo, else is not allowed
BOnly if you have a finally clause
CYes, but it runs only if an exception occurs
DYes, it runs if no exception occurs
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.