我正在尝试将一些Python代码转换为Ruby。 Ruby中有与Python中的try语句等效的东西吗?

最佳答案

以此为例:

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

Python中的等效代码为:
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.')

关于python - Ruby相当于Python的 “try”吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18705373/

10-10 21:25