Challenge - 5 Problems
Ruby Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple rescue block
What is the output of this Ruby code?
Ruby
def test begin 1 / 0 rescue ZeroDivisionError "divided by zero" end end puts test
Attempts:
2 left
💡 Hint
Look at what happens when dividing by zero inside the begin block and how rescue handles it.
✗ Incorrect
The division by zero raises a ZeroDivisionError, which is caught by the rescue block. The rescue block returns the string "divided by zero", which is then printed.
❓ Predict Output
intermediate2:00remaining
Return value with ensure block
What will this Ruby code print?
Ruby
def example begin return 1 ensure puts "ensure block" end end puts example
Attempts:
2 left
💡 Hint
Remember that ensure runs even if there is a return inside begin.
✗ Incorrect
The method returns 1, but before returning, the ensure block runs and prints "ensure block". Then the returned value 1 is printed by puts.
🔧 Debug
advanced2:00remaining
Identify the error in rescue syntax
Which option contains a syntax error in the rescue block?
Ruby
begin puts 10 / 0 rescue ZeroDivisionError => e puts e.message end
Attempts:
2 left
💡 Hint
Check the placement of the exception class and variable in rescue syntax.
✗ Incorrect
Option D places the exception variable 'e' before the exception class, which is invalid syntax. The correct syntax is 'rescue ExceptionClass => variable'.
🧠 Conceptual
advanced2:00remaining
Behavior of nested begin/rescue blocks
What will be the output of this Ruby code?
Ruby
begin begin raise "error" rescue RuntimeError puts "inner rescue" raise end rescue puts "outer rescue" end
Attempts:
2 left
💡 Hint
Consider how the inner rescue handles the error and what happens when it re-raises it.
✗ Incorrect
The inner rescue catches the RuntimeError and prints "inner rescue". Then it re-raises the error, which is caught by the outer rescue that prints "outer rescue".
❓ Predict Output
expert2:00remaining
Output with multiple rescue clauses and ensure
What is the output of this Ruby code?
Ruby
def test begin raise ArgumentError, "wrong argument" rescue ZeroDivisionError puts "zero division" rescue ArgumentError => e puts e.message ensure puts "always runs" end end test
Attempts:
2 left
💡 Hint
Check which rescue clause matches the raised exception and the order of ensure execution.
✗ Incorrect
The raised ArgumentError matches the second rescue clause, printing its message "wrong argument". The ensure block always runs, printing "always runs" after.