簡體   English   中英

Ruby 相當於 Python 的“try”?

[英]Ruby equivalent for Python's “try”?

我正在嘗試將一些 Python 代碼轉換為 Ruby。 Ruby 中是否有與 Python 中的try語句等效的語句?

以此為例:

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.')
 begin
     some_code
 rescue
      handle_error  
 ensure 
     this_code_is_always_executed
 end

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

如果要捕獲特定類型的異常,請使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM