0
0
Rubyprogramming~10 mins

Multiple rescue clauses in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to rescue a ZeroDivisionError.

Ruby
begin
  result = 10 / 0
rescue [1]
  puts "Cannot divide by zero"
end
Drag options to blanks, or click blank then click option'
AZeroDivisionError
BTypeError
CNameError
DArgumentError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong error class like TypeError or NameError.
Not rescuing any error and letting the program crash.
2fill in blank
medium

Complete the code to rescue an IOError.

Ruby
begin
  file = File.open(__FILE__)
  file.close
  file.read
rescue [1]
  puts "IO operation failed"
end
Drag options to blanks, or click blank then click option'
AZeroDivisionError
BIOError
CRuntimeError
DNoMethodError
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated error classes like ZeroDivisionError.
Not rescuing the correct error causes the program to crash.
3fill in blank
hard

Fix the error in the rescue clause to handle both ZeroDivisionError and IOError.

Ruby
begin
  # some code that may raise errors
rescue [1], IOError
  puts "Handled an error"
end
Drag options to blanks, or click blank then click option'
AStandardError
BRuntimeError
CZeroDivisionError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic error like RuntimeError which may not catch the specific error.
Using Exception which is too broad and not recommended.
4fill in blank
hard

Fill both blanks to rescue ArgumentError and NoMethodError separately.

Ruby
begin
  # risky code
rescue [1]
  puts "Argument error caught"
rescue [2]
  puts "No method error caught"
end
Drag options to blanks, or click blank then click option'
AArgumentError
BZeroDivisionError
CNoMethodError
DIOError
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up error classes in rescue clauses.
Using the same error class for both rescue clauses.
5fill in blank
hard

Fill all three blanks to rescue RuntimeError, TypeError, and StandardError in one rescue clause.

Ruby
begin
  # code that may raise errors
rescue [1], [2], [3]
  puts "An error was rescued"
end
Drag options to blanks, or click blank then click option'
ARuntimeError
BTypeError
CStandardError
DNoMethodError
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated error classes like NoMethodError here.
Trying to rescue errors in separate rescue clauses instead of one.