In Ruby, exception handling is done using the begin
, rescue
, else
, and ensure
blocks. Here’s a basic structure of a begin-rescue block:
begin
# Code that might raise an exception
result = 10 / 0 # Example: Division by zero
rescue ExceptionType => e
# Handle the exception
puts "An exception of type #{e.class} occurred: #{e.message}"
else
# Code to be executed if no exception occurs
puts "No exception occurred."
ensure
# Code that will be executed no matter what
puts "This code will always run."
end
Let’s break down the components:
- The
begin
block contains the code that might raise an exception. - The
rescue
block catches and handles the exception. You can catch specific exception types or a generalException
type. - The
else
block contains code that will be executed if no exception occurs. - The
ensure
block contains code that will be executed no matter what, whether an exception occurred or not.
Example with a specific exception:
begin
print "Enter a number: "
num = gets.chomp.to_i
result = 10 / num
rescue ZeroDivisionError
puts "Cannot divide by zero."
rescue => e
puts "An unexpected error occurred: #{e.message}"
else
puts "Result: #{result}"
ensure
puts "Execution completed."
end
In this example:
- If the user enters 0, a
ZeroDivisionError
is caught. - If the user enters a non-numeric value, the general
rescue
block catches the exception. - If the user enters a valid number, the result is displayed in the
else
block. - The
ensure
block ensures that the final message is printed regardless of the outcome.
As with any language, it’s good practice to catch only the exceptions you expect and handle them appropriately. Avoid catching overly broad exceptions unless necessary.