- 函
raise式用來指出發生錯誤或例外狀況。 例外狀況物件中擷取錯誤的相關信息。 - 函
reraise式用來將已處理的例外狀況傳播至呼叫鏈結。
語法
raise (expression)
備註
函 raise 式會產生例外狀況物件,並起始堆疊回溯程式。 堆疊回溯程式是由 Common Language Runtime (CLR) 所管理,因此此程序的行為與任何其他 .NET 語言的行為相同。 堆疊回溯程式是搜尋符合所產生例外狀況的例外狀況處理程式。 如果有搜尋,則搜尋會從目前的 try...with 表達式開始。 會依序檢查區塊中的每個 with 模式。 找到相符的例外狀況處理程式時,系統會將例外狀況視為已處理;否則,堆疊會解除復原,並 with 封鎖呼叫鏈結,直到找到相符的處理程序為止。 當堆疊回溯時,呼叫鏈結中遇到的任何 finally 區塊也會依序執行。
函 raise 式相當於 throw C# 或 C++。
下列程式代碼範例說明如何使用 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式不能用於with計算清單、陣列、序列或計算運算式中的建構區塊trywith/,包括 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@()