Ruby相当于Python的“尝试”?

时间:2013-09-09 19:19:34

标签: python ruby try-catch language-comparisons

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

3 个答案:

答案 0 :(得分:55)

以此为例:

begin  # "try" block
    puts 'I am before the raise.'  
    raise 'An error has occured.' # 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 occured.') # 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.'

答案 1 :(得分:8)

 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

详细信息:http://crodrigues.com/try-catch-finally-equivalent-in-ruby/

答案 2 :(得分:0)

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

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

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

这里是一个例子:

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