Error handling uses rescue to catch problems in your code so the program can keep running without crashing.
When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When connecting to the internet and the connection might fail.
When converting user input to a number that might be invalid.
Syntax
Ruby
begin# code that might cause an errorrescue SomeErrorClass
# code to run if error happensend
begin starts the block where errors might happen.
rescue catches the error and lets you handle it safely.
Examples
This catches the error when dividing by zero and prints a message instead of crashing.
Ruby
begin1 / 0rescue ZeroDivisionError
puts"Can't divide by zero!"end
This handles the error if the file does not exist.
Ruby
begin
file = File.read('missing.txt')
rescue Errno::ENOENT
puts"File not found!"end
This catches the error when trying to convert a bad string to a number.
Ruby
begin
number = Integer('abc')
rescue ArgumentError
puts"Invalid number!"end
Sample Program
This program asks the user for a number and divides 10 by it. It uses rescue to handle if the user enters zero or something that is not a number.
Ruby
beginputs"Enter a number to divide 10 by:"
input = gets.chomp
divisor = Integer(input)
result = 10 / divisor
puts"Result is #{result}"rescue ZeroDivisionError
puts"You can't divide by zero!"rescue ArgumentError
puts"That's not a valid number!"end
OutputSuccess
Important Notes
You can have multiple rescue clauses to handle different errors.
If you don't handle errors, your program might stop unexpectedly.
Summary
rescue helps your program handle errors without crashing.
Use rescue to catch specific errors and respond nicely.
This makes your programs more user-friendly and reliable.
Practice
(1/5)
1. Why do Ruby programs use rescue in error handling?
easy
A. To make the code shorter
B. To speed up the program execution
C. To catch errors and prevent the program from crashing
D. To automatically fix all errors
Solution
Step 1: Understand the purpose of rescue
rescue is used to catch errors that happen during program execution.
Step 2: Recognize the benefit of catching errors
Catching errors prevents the program from crashing and allows it to handle problems gracefully.
Final Answer:
To catch errors and prevent the program from crashing -> Option C
Quick Check:
rescue catches errors = C [OK]
Hint: Remember: rescue stops crashes by catching errors [OK]
Common Mistakes:
Thinking rescue speeds up code
Believing rescue fixes errors automatically
Confusing rescue with code shortening
2. Which of the following is the correct syntax to handle errors using rescue in Ruby?
easy
A. error do
# handle error
end
B. try
# code
catch
# error handling
end
C. if error
# handle error
end
D. begin
# code
rescue
# error handling
end
Solution
Step 1: Identify Ruby's error handling syntax
Ruby uses begin and rescue blocks to handle errors.
Step 2: Compare options to Ruby syntax
begin
# code
rescue
# error handling
end matches Ruby's syntax exactly; others use syntax from other languages or incorrect forms.
Final Answer:
begin\n # code\nrescue\n # error handling\nend -> Option D
Quick Check:
Ruby uses begin-rescue-end = D [OK]
Hint: Remember Ruby uses begin and rescue keywords [OK]
Common Mistakes:
Using try-catch like other languages
Using if statements for error handling
Misplacing rescue outside begin-end
3. What will be the output of this Ruby code?
begin
puts 10 / 0
rescue ZeroDivisionError
puts "Cannot divide by zero!"
end
medium
A. 0
B. Cannot divide by zero!
C. Infinity
D. Error: division by zero
Solution
Step 1: Identify the error raised
Dividing 10 by 0 raises a ZeroDivisionError in Ruby.
Step 2: Check the rescue block handling
The rescue block catches ZeroDivisionError and prints "Cannot divide by zero!".
Final Answer:
Cannot divide by zero! -> Option B
Quick Check:
ZeroDivisionError caught prints message = A [OK]
Hint: Look for error type matched in rescue block [OK]
Common Mistakes:
Expecting program to crash with error message
Thinking division by zero returns 0 or Infinity
Ignoring rescue block effect
4. Find the error in this Ruby code snippet:
begin
puts 5 + '3'
rescue
puts "Error caught!"
end
medium
A. Adding integer and string causes a TypeError
B. The rescue block is missing the error type
C. The begin keyword is not needed
D. The puts statement is incorrect
Solution
Step 1: Analyze the operation inside begin block
Adding 5 (integer) and '3' (string) causes a TypeError in Ruby.
Step 2: Understand rescue block behavior
The rescue block catches the error and prints "Error caught!"; the error is due to incompatible types.
Final Answer:
Adding integer and string causes a TypeError -> Option A
Quick Check:
TypeError from adding int and string = A [OK]
Hint: Check data types when rescue catches errors [OK]
Common Mistakes:
Thinking rescue must specify error type
Believing begin is optional here
Assuming puts causes error
5. You want to handle different errors separately in Ruby. Which code correctly uses rescue to handle ZeroDivisionError and NoMethodError differently?
begin
# some code
rescue ZeroDivisionError
puts "Divide by zero error"
rescue NoMethodError
puts "Method not found error"
end
hard
A. This code correctly handles each error with separate rescue blocks
B. You cannot have multiple rescue blocks; only one is allowed
C. You must use if statements inside rescue to check error type
D. Rescue only catches StandardError, so this won't work
Solution
Step 1: Understand multiple rescue usage
Ruby allows multiple rescue clauses to handle different error types separately.
Step 2: Verify code matches correct syntax
The code uses separate rescue blocks for ZeroDivisionError and NoMethodError, which is valid.
Final Answer:
This code correctly handles each error with separate rescue blocks -> Option A
Quick Check:
Multiple rescue blocks handle errors separately = B [OK]
Hint: Use multiple rescue blocks for different errors [OK]
Common Mistakes:
Thinking only one rescue block is allowed
Trying to use if inside rescue instead
Believing rescue can't catch specific errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.