例外狀況:引發和重新引發函式

  • raise 函式用於指出發生錯誤或例外狀況。 例外狀況物件會擷取錯相關的資訊。
  • reraise 函式用於將已處理的例外狀況傳播至呼叫鏈。

語法

raise (expression)

備註

raise 函式會產生例外狀況物件,並啟動堆疊回溯流程。 堆疊回溯流程通用語言執行平台 (CLR) 所管理,因此該流程的行為與其在任何其他 .NET 語言中的行為相同。 堆疊回溯流程可搜尋符合所產生例外狀況的例外狀況處理常式。 搜尋會從目前的 try...with 運算式開始進行 (若有)。 依序檢查 with 區塊中的每個模式。 找到相符的例外狀況處理常式時,系統會將例外狀況視為已處理,否則便會回溯堆疊;而 with 會封鎖呼叫鏈,直到找到相符的處理常式為止。 回溯堆疊時,也會依序執行呼叫鏈中找到的任何 finally 區塊。

raise 函式相當於 C# 或 C++ 中的 throw

下列程式碼範例說明如何使用 raise 函式來產生例外狀況。

exception InnerError of string
exception OuterError of string

let function1 x y =
   try
     try
        if x = y then raise (InnerError("inner"))
        else raise (OuterError("outer"))
     with
      | InnerError(str) -> printfn "Error1 %s" str
   finally
      printfn "Always print this."


let function2 x y =
  try
     function1 x y
  with
     | OuterError(str) -> printfn "Error2 %s" str

function2 100 100
function2 100 10

raise 函式也可以用於引發 .NET 例外狀況,如下列範例所示。

let divide x y =
  if (y = 0) then raise (System.ArgumentException("Divisor cannot be zero!"))
  else
     x / y

重新引發例外狀況

reraise 函式可用於 with 區塊,以將已處理的例外狀況傳播至呼叫鏈。 reraise 不接受例外狀況運算元。 當方法將來自呼叫端的引數傳遞給某個程式庫方法,且程式庫方法引發了必須傳遞給呼叫端的例外狀況時,這個方法最實用。

reraise 函式不可用於計算清單、陣列、序列或計算運算式中的 try/with 建構 with 區塊,包括 task { .. }async { .. }

open System

let getFirstCharacter(value: string) =
    try
        value[0]
    with :? IndexOutOfRangeException as e ->
        reraise()

let s = getFirstCharacter("")
Console.WriteLine($"The first character is {s}")

// The example displays the following output:
//   System.IndexOutOfRangeException: Index was outside the bounds of the array.
//      at System.String.get_Chars(Int32 index)
//      at getFirstCharacter(String value)
//      at <StartupCode>.main@()

另請參閱