0
0
Rubyprogramming~20 mins

Begin/rescue/end blocks in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
AZeroDivisionError
Bdivided by zero
C0
DInfinity
Attempts:
2 left
💡 Hint
Look at what happens when dividing by zero inside the begin block and how rescue handles it.
Predict Output
intermediate
2: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
A1
Bensure block
C
ensure block
1
D
1
ensure block
Attempts:
2 left
💡 Hint
Remember that ensure runs even if there is a return inside begin.
🔧 Debug
advanced
2: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
A
begin
  puts 10 / 0
rescue ZeroDivisionError => e
  puts e.message
end
B
begin
  puts 10 / 0
rescue ZeroDivisionError, NameError => e
  puts e.message
end
C
begin
  puts 10 / 0
rescue ZeroDivisionError
  puts 'error'
end
D
begin
  puts 10 / 0
rescue => e ZeroDivisionError
  puts e.message
end
Attempts:
2 left
💡 Hint
Check the placement of the exception class and variable in rescue syntax.
🧠 Conceptual
advanced
2: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
A
inner rescue
outer rescue
B
outer rescue
inner rescue
Cinner rescue
Douter rescue
Attempts:
2 left
💡 Hint
Consider how the inner rescue handles the error and what happens when it re-raises it.
Predict Output
expert
2: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
A
wrong argument
always runs
B
zero division
always runs
C
always runs
wrong argument
D
ArgumentError
always runs
Attempts:
2 left
💡 Hint
Check which rescue clause matches the raised exception and the order of ensure execution.