Ruby中与Python的"try"相当的语法是什么?
Ruby中与Python的"try"相当的语法是什么?
我正在尝试将一些Python代码转换为Ruby。在Ruby中是否有与Python中的try
语句相当的语句?
admin 更改状态以发布 2023年5月22日
begin some_code rescue handle_error ensure this_code_is_always_executed end
细节:http://crodrigues.com/try-catch-finally-equivalent-in-ruby/
使用这个作为示例:
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
相等的 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.')