Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-zero number does not cause an error.
✗ Incorrect
The rescue block catches the ZeroDivisionError when dividing by zero.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic error like StandardError does not specifically catch file errors.
✗ Incorrect
Errno::ENOENT is the error raised when a file is not found in Ruby.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using SyntaxError or TypeError which are not raised here.
✗ Incorrect
ArgumentError is raised when Integer conversion fails due to invalid input.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning nil instead of a number.
✗ Incorrect
ZeroDivisionError is rescued and method returns 0 as fallback.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing error classes or using wrong divisor.
✗ Incorrect
Dividing by 0 raises ZeroDivisionError, missing file raises Errno::ENOENT.