Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start a block that handles exceptions.
Ruby
begin puts 'Hello world' [1] end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ensure' instead of 'rescue' to catch exceptions.
✗ Incorrect
The rescue keyword starts the block that catches exceptions in Ruby.
2fill in blank
mediumComplete the code to print an error message when an exception occurs.
Ruby
begin 1 / 0 rescue => [1] puts "Error: #{e.message}" end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names other than 'e' which are not referenced in the code.
✗ Incorrect
The variable e is commonly used to hold the exception object in a rescue block.
3fill in blank
hardFix the error in the rescue block to correctly handle exceptions.
Ruby
begin file = File.open('nonexistent.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 'FileNotFoundError' which is not a Ruby exception class.
✗ Incorrect
StandardError catches the Errno::ENOENT exception for file not found errors in Ruby.
4fill in blank
hardFill both blanks to retry the operation if an exception occurs.
Ruby
begin puts 'Trying...' 1 / 0 rescue [1] => e puts e.message [2] end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' instead of 'retry' to repeat the block.
✗ Incorrect
ZeroDivisionError catches the division error, and retry repeats the begin block.
5fill in blank
hardFill the two blanks to ensure a message is printed whether or not an exception occurs.
Ruby
begin puts 'Start' 1 / 0 rescue [1] => e puts e.message [2] puts 'Always runs' end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finally' which is not a Ruby keyword.
✗ Incorrect
ZeroDivisionError handles division errors, and ensure runs code always after begin/rescue.