【问题标题】:Ruby equivalent for Python's "try"?Ruby 等效于 Python 的“尝试”?
【发布时间】:2013-09-13 08:43:30
【问题描述】:

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

【问题讨论】:

  • 请显示一个代码!
  • 查找 Ruby rescue(和 raise

标签: python python-3.x ruby try-catch language-comparisons


【解决方案1】:
 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

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

【讨论】:

  • 很好的链接!真的很有帮助。
【解决方案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 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 示例。我会试试看!哈哈!
  • 还有一个古怪的 else 子句,只有在没有触发异常时才会执行。
  • 这是最简单易懂的回答,谢谢谢谢
  • 从形式和内容的角度来看,这是关于 SO 的最佳答案之一;非常感谢
【解决方案3】:

如果要捕获特定类型的异常,请使用:

begin
    # Code
rescue ErrorClass
    # Handle Error
ensure
    # Optional block for code that is always executed
end

这种方法比单纯的“rescue”块更可取,因为没有参数的“rescue”会捕获 StandardError 或其任何子类,包括 NameError 和 TypeError。

这是一个例子:

begin
    raise "Error"
rescue RuntimeError
    puts "Runtime error encountered and rescued."
end

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 2013-11-30
    • 2018-06-29
    • 2014-10-18
    • 2014-09-02
    • 2015-05-24
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多