Ruby equivalent for Python's "try"?

PythonPython 3.xRubyTry CatchLanguage Comparisons

Python Problem Overview


I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the try statement in Python?

Python Solutions


Solution 1 - Python

Use this as an example:

begin  # "try" block
    puts 'I am before the raise.'  
    raise 'An error has occurred.' # optionally: `raise Exception, "message"`
    puts 'I am after the raise.'   # won't be executed
rescue # optionally: `rescue Exception => ex`
    puts 'I am rescued.'
ensure # will always get executed
    puts 'Always gets executed.'
end 

The equivalent code in Python would be:

try:     # try block
    print('I am before the raise.')
    raise Exception('An error has occurred.') # throw an exception
    print('I am after the raise.')            # won't be executed
except:  # optionally: `except Exception as ex:`
    print('I am rescued.')
finally: # will always get executed
    print('Always gets executed.')

Solution 2 - Python

 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

Details: http://crodrigues.com/try-catch-finally-equivalent-in-ruby/

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthatonegirloView Question on Stackoverflow
Solution 1 - PythonÓscar LópezView Answer on Stackoverflow
Solution 2 - PythonzengrView Answer on Stackoverflow
Solution 3 - PythonZagsView Answer on Stackoverflow