在 Ruby 中使用 begin 和 rescue 處理異常
    
    
            Nurudeen Ibrahim
    2023年1月30日
    
    Ruby
    Ruby Exception
    
 
本文將討論在 Ruby 中使用 begin 和 rescue 處理異常。
Ruby 中異常處理的一般語法
在 Ruby 中,begin 和 rescue 關鍵字通過將可能引發異常的程式碼包含在 begin-end 塊中來處理異常。
begin
  # code that might raise an exception
rescue AnExceptionClass => a_variable
  # code that deals with some exception
rescue AnotherException => another_variable
  # code that deals with another exception
else
  # code that runs only if no exception was raised
ensure
  # code that always runs no matter what
end
在 Ruby 中使用 begin 和 rescue 處理異常
下面的示例顯示了 begin 和 rescue 關鍵字。
示例程式碼:
def do_arithmetic(a, b)
    begin
        answer = (b + a) / (a * b)
        puts answer
    rescue ZeroDivisionError => e
        puts "Custom Error: #{e.message}"
    rescue TypeError => e
        puts "Custom Error: #{e.message}"
    ensure
        puts "Done."
    end
end
do_arithmetic(2, 2)
do_arithmetic(0, 2)
do_arithmetic("David", 2)
輸出:
# first output
1
Done.
# second output
Custom Error: divided by 0
Done.
# third output
Custom Error: String can't be coerced into Integer
Done.
組合多個異常並在同一個 rescue 塊中處理它們也是可能的。上面示例中的 ZeroDivisionError, 和 TypeError 異常可以在下面一起執行。
def do_arithmetic(a, b)
    begin
        answer = (b + a) / (a * b)
        puts answer
    rescue ZeroDivisionError, TypeError => e
        puts "Custom Error: #{e.message}"
    ensure
        puts "Done."
    end
end
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe