Ruby equivalent for Python's "try"? Ruby equivalent for Python's "try"? python python

Ruby equivalent for Python's "try"?


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 executedrescue # 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 executedexcept:  # optionally: `except Exception as ex:`    print('I am rescued.')finally: # will always get executed    print('Always gets executed.')


If you want to catch a particular type of exception, use:

begin    # Coderescue ErrorClass    # Handle Errorensure    # Optional block for code that is always executedend

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