I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the try
statement in Python?
Ruby equivalent for Python's "try"?
51.7k views Asked by thatonegirlo At
3
There are 3 answers
1
On
begin
some_code
rescue
handle_error
ensure
this_code_is_always_executed
end
Details: http://crodrigues.com/try-catch-finally-equivalent-in-ruby/
0
On
If you want to catch a particular type of exception, use:
begin
# Code
rescue ErrorClass
# Handle Error
ensure
# Optional block for code that is always executed
end
This approach is preferable to a bare "rescue" block as "rescue" with no arguments will catch a StandardError or any child class thereof, including NameError and TypeError.
Here is an example:
begin
raise "Error"
rescue RuntimeError
puts "Runtime error encountered and rescued."
end
Use this as an example:
The equivalent code in Python would be: