Error Handling in Ruby
Ruby uses exceptions for error handling, which can be caught using begin, rescue, and ensure blocks.
Basic Error Handling
Use begin and rescue to handle exceptions.
begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
end
Multiple Rescue Clauses
You can handle multiple types of exceptions by adding multiple rescue clauses.
begin
# Code that may raise an exception
file = File.open("nonexistent_file.txt")
content = file.read
rescue Errno::ENOENT => e
puts "File not found: #{e.message}"
rescue StandardError => e
puts "An error occurred: #{e.message}"
end
Retrying Code
Use retry to re-execute the begin block after an exception is rescued.
attempts = 0
begin
attempts += 1
puts "Attempt #{attempts}"
raise "An error occurred"
rescue => e
retry if attempts < 3
puts "Failed after #{attempts} attempts"
end
Raising Exceptions
You can raise exceptions explicitly using the raise keyword.
def divide(a, b)
raise ArgumentError, "Divisor cannot be zero" if b == 0
a / b
end
begin
result = divide(10, 0)
rescue ArgumentError => e
puts "Error: #{e.message}"
end
Custom Exceptions
You can define custom exceptions by subclassing StandardError.
class CustomError < StandardError
end
begin
raise CustomError, "Something went wrong!"
rescue CustomError => e
puts "Caught custom error: #{e.message}"
end
Ensure Block
The ensure block is used to execute code regardless of whether an exception was raised.
begin
file = File.open("example.txt")
content = file.read
rescue => e
puts "Error: #{e.message}"
ensure
file.close if file
end
Best Practices
- Be Specific: Rescue specific exceptions rather than using a generic
rescue. - Log Errors: Always log exceptions for debugging purposes.
- Use Ensure: Use
ensureto clean up resources like file handles or database connections. - Avoid Silent Failures: Avoid rescuing exceptions without logging or handling them appropriately.