Ruby 等同于 Python 的“try”?

新手上路,请多包涵

我正在尝试将一些 Python 代码转换为 Ruby。 Ruby 中是否有与 Python 中的 try 语句等价的语句?

原文由 thatonegirlo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 745
2 个回答

以此为例:

 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.')

原文由 Óscar López 发布,翻译遵循 CC BY-SA 4.0 许可协议

 begin
     some_code
 rescue
      handle_error
 ensure
     this_code_is_always_executed
 end

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

原文由 zengr 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题