What is the Ruby equivalent of Python’s try statement?
I’m converting some Python code to Ruby and need to handle exceptions. Does Ruby have a try-catch mechanism similar to Python’s try-except? If so, how does Ruby try-catch work?
What is the Ruby equivalent of Python’s try statement?
I’m converting some Python code to Ruby and need to handle exceptions. Does Ruby have a try-catch mechanism similar to Python’s try-except? If so, how does Ruby try-catch work?
In Python, you use try-except to handle exceptions. Ruby has a similar mechanism using begin-rescue.
Here’s how it works:
begin
# Code that may raise an exception
num = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
end
This is equivalent to:
try:
num = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
The begin block contains the code that might fail, and rescue catches the error."
That’s a good start! Ruby also allows handling multiple exception types, just like Python:
begin
# Some risky operation
raise ArgumentError, "Invalid argument"
rescue ZeroDivisionError
puts "Caught division by zero"
rescue ArgumentError => e
puts "Caught argument error: #{e.message}"
end
Additionally, Ruby has an ensure block, which is similar to Python’s finally. This is useful for cleanup tasks like closing files or releasing resources: This guarantees that ensure runs no matter what happens in begin or rescue."
Building on that, if you want to raise custom exceptions, Ruby provides raise, just like Python’s raise:
def check_age(age)
raise ArgumentError, "Age must be greater than 18" if age < 18
end
begin
check_age(16)
rescue ArgumentError => e
puts "Caught an error: #{e.message}"
end
If you need more structured exception handling, you can even define custom exception classes:
class CustomError < StandardError; end
begin
raise CustomError, "Something went wrong!"
rescue CustomError => e
puts "Caught custom error: #{e.message}"
end