Ruby 相当于 Python 的“try”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18705373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:31:49  来源:igfitidea点击:

Ruby equivalent for Python's "try"?

pythonrubytry-catchlanguage-comparisons

提问by thatonegirlo

I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the trystatement in Python?

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

采纳答案by óscar López

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 executed
rescue # 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:

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

回答by zengr

 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

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

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

回答by Zags

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

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

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

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.

这种方法比裸露的“救援”块更可取,因为没有参数的“救援”将捕获 StandardError 或其任何子类,包括 NameError 和 TypeError。

Here is an example:

下面是一个例子:

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