0
0
Rubyprogramming~10 mins

Why error handling uses rescue in Ruby - Test Your Understanding

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

Complete the code to handle errors using rescue.

Ruby
begin
  puts 10 / [1]
rescue ZeroDivisionError
  puts 'Cannot divide by zero'
end
Drag options to blanks, or click blank then click option'
A0
Bnil
C2
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-zero number does not cause an error.
2fill in blank
medium

Complete the code to rescue from a generic error.

Ruby
begin
  file = File.open('missing.txt')
rescue [1]
  puts 'File not found'
end
Drag options to blanks, or click blank then click option'
AArgumentError
BStandardError
CFileNotFoundError
DErrno::ENOENT
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic error like StandardError does not specifically catch file errors.
3fill in blank
hard

Fix the error in the rescue syntax.

Ruby
begin
  num = Integer('abc')
rescue [1]
  puts 'Invalid number'
end
Drag options to blanks, or click blank then click option'
ANameError
BSyntaxError
CArgumentError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using SyntaxError or TypeError which are not raised here.
4fill in blank
hard

Fill both blanks to handle division errors and print a message.

Ruby
def divide(a, b)
  a / b
rescue [1] => e
  puts "Error: #{e}"
  return [2]
end
Drag options to blanks, or click blank then click option'
AZeroDivisionError
Bnil
CTypeError
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning nil instead of a number.
5fill in blank
hard

Fill all three blanks to rescue multiple errors and print custom messages.

Ruby
begin
  puts 10 / [1]
  file = File.open('data.txt')
rescue [2] => e
  puts "Division error: #{e}"
rescue [3] => e
  puts "File error: #{e}"
end
Drag options to blanks, or click blank then click option'
A0
BZeroDivisionError
CErrno::ENOENT
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing error classes or using wrong divisor.