Ruby相当于python尝试

tha*_*rlo 42 ruby python language-comparisons try-catch

我是编码的主要菜鸟.我开始学习Python,但不是粉丝,而是转向我喜欢的Ruby.现在我正在尝试将一些python代码转换为ruby而我陷入了python的"尝试"是一个相当于python的"尝试"的红宝石

Ósc*_*pez 69

以此为例:

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 
Run Code Online (Sandbox Code Playgroud)

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.'
Run Code Online (Sandbox Code Playgroud)

  • 哦真棒!感谢您还提供了一个 python 示例。我会试试看!哈哈! (3认同)
  • 还有一个奇怪的“else”子句,只有在没有触发异常的情况下才会执行。 (3认同)
  • 从形式和内容的角度来看,SO 的最佳答案之一;非常感谢 (2认同)

zen*_*ngr 9

 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end
Run Code Online (Sandbox Code Playgroud)

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