Search code examples
pythonpython-3.xrubytry-catchlanguage-comparisons

Ruby equivalent for Python's "try"?


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


Solution

  • 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 StandardError => 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.')