0
0
Rubyprogramming~10 mins

Begin/rescue/end blocks 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 start a block that handles exceptions.

Ruby
begin
  puts 'Hello world'
[1]
end
Drag options to blanks, or click blank then click option'
Aensure
Brescue
Ccatch
Dfinally
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ensure' instead of 'rescue' to catch exceptions.
2fill in blank
medium

Complete 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'
Ae
Berror
Cex
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names other than 'e' which are not referenced in the code.
3fill in blank
hard

Fix 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'
AFileNotFoundError
BException
CIOError
DStandardError
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'FileNotFoundError' which is not a Ruby exception class.
4fill in blank
hard

Fill 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'
AZeroDivisionError
Bretry
CStandardError
Draise
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' instead of 'retry' to repeat the block.
5fill in blank
hard

Fill 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'
AZeroDivisionError
Bensure
Crescue
Dfinally
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finally' which is not a Ruby keyword.