Ruby相当于Python的“尝试”?

问题描述 投票:34回答:3

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

python ruby try-catch language-comparisons
3个回答
61
投票

以此为例:

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

9
投票
 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

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


0
投票

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

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

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

这是一个例子:

begin
    raise "Error"
rescue RuntimeError
    puts "Runtime error encountered and rescued."
end
© www.soinside.com 2019 - 2024. All rights reserved.