63

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

4

3 回答 3

117

以此为例:

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.')
于 2013-09-09T19:22:52.397 回答
13
 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

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

于 2013-09-09T19:21:55.543 回答
2

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

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
于 2019-04-01T20:29:50.900 回答