Ruby 中的 try...catch
    
    
            Nurudeen Ibrahim
    2023年1月30日
    
    Ruby
    Ruby Exception
    
 
異常是在程式執行期間發生的不希望發生的事件。一個例子是當程式試圖將一個數字除以零時出現 ZeroDivisionError。搶救異常是一種優雅地處理它的方法,因此它不會使程式崩潰。
Ruby 中的異常通常由兩個子句組成,begin 和 rescue。begin 子句相當於 Python 或任何其他類似程式語言中的 try,而 rescue 相當於 catch。下面是語法。
begin
  # do something that might cause an exception
rescue
  # handle the exception here
end
讓我們編寫一個簡單的程式,在給定商品的銷售價格和成本價格的情況下計算利潤百分比。
示例程式碼:
def profit_percentage(selling_price, cost_price)
  profit = selling_price - cost_price
  "#{(profit.fdiv(cost_price) * 100)}%"
end
puts profit_percentage(30, 20)
puts profit_percentage(30, nil)
輸出:
50.0%
nil can't be coerced into Integer (TypeError)
正如我們在上面的輸出中看到的,第二次呼叫 profit_percentage 引發了錯誤,因為我們將 nil 作為 cost_price 傳遞。現在讓我們來說明一下我們可以挽救這個異常的不同方法。
使用 Ruby 中的通用錯誤訊息進行救援
使用通用錯誤訊息進行救援並不總是有幫助,因為它不會揭示異常的根本原因。
示例程式碼:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue
    "An unknown error occurred."
  end
end
puts profit_percentage(30, nil)
輸出:
An unknown error occurred.
使用 Ruby 異常中的訊息進行救援
如果你對引發的異常型別不感興趣,而只對錯誤訊息感興趣,則此方法會派上用場。
示例程式碼:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue => e
    e
  end
end
puts profit_percentage(30, nil)
輸出:
nil can't be coerced into Integer
在 Ruby 中搶救特定型別的異常
如果你只對處理特定型別的異常感興趣,這將很有幫助。
示例程式碼:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue TypeError
    "An argument of invalid type was detected"
  end
end
puts profit_percentage(30, nil)
輸出:
An argument of invalid type was detected
此外,值得一提的是,還有另一個可選子句 ensure,這在你總是需要執行某些程式碼而不管是否引發異常的情況下可能會有所幫助。
示例程式碼:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    puts "#{(profit.fdiv(cost_price) * 100)}%"
  rescue => e
    puts e
  ensure
    puts "Done calculating profit %"
  end
end
profit_percentage(30, 20)
profit_percentage(30, nil)
輸出:
50.0%
Done calculating profit %
nil can't be coerced into Integer
Done calculating profit %
如上面的輸出所示,ensure 子句中的程式碼在 profit_percentage 的兩個呼叫中都被觸發。該子句通常用於在執行某些檔案操作後需要關閉檔案時,無論是否發生異常。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe