Error Handling
In Ruby, error handling is typically done using begin
, rescue
, and ensure
blocks.
begin
# Code that might raise an exception
result = 10 / 0
rescue ZeroDivisionError => e
# Handle specific exception
puts "Error: #{e.message}"
rescue StandardError => e
# Handle other types of exceptions
puts "An unexpected error occurred: #{e.message}"
ensure
# Code that will be executed no matter what (optional)
puts "This code always runs."
end
- The
begin
block contains the code that might raise an exception. - The
rescue
block catches specific types of exceptions. In this case,ZeroDivisionError
andStandardError
are caught. - The
ensure
block contains code that will be executed whether an exception occurs or not. It's optional and can be omitted if not needed.
Handling Multiple Exceptions
You can have multiple rescue
blocks to handle different types of exceptions.
begin
# Code that might raise an exception
result = 10 / 0
rescue ZeroDivisionError => e
puts "Error: Division by zero - #{e.message}"
rescue ArgumentError => e
puts "Error: Invalid argument - #{e.message}"
rescue StandardError => e
puts "An unexpected error occurred: #{e.message}"
end
Using else
The else
block contains code that will be executed if no exception occurs in the begin
block.
begin
# Code that might raise an exception
result = 10 / 2
rescue ZeroDivisionError => e
puts "Error: Division by zero - #{e.message}"
else
# Code to execute if no exception occurs
puts "Result: #{result}"
end
Raising Exceptions
You can raise
exceptions using the raise keyword, specifying the exception type and an optional error message.
def some_method(value)
raise ArgumentError, "Invalid value" if value.nil?
# Rest of the method code
end
Code Challenge
Write a Ruby function
safe_divide
that takes two parameters (numerator
anddenominator
) and returns the result of the division. However, ensure that your function handles potential division by zero errors gracefully.
Loading...
> code result goes here