例外狀況:try...with 運算式

本主題將描述 try...with 運算式,此運算式用於處理 F# 中的例外狀況。

語法

try
    expression1
with
| pattern1 -> expression2
| pattern2 -> expression3
...

備註

try...with 運算式會用來處理 F# 中的例外狀況。 其類似於 C# 中的 try...catch 陳述式。 在上述陳述式中,expression1 中的程式碼可能會產生例外狀況。 try...with 運算式會傳回值。 如果未擲回例外狀況,整個運算式會傳回 expression1 的值。 如果擲回例外狀況,則會接著比較每個模式與例外狀況,並針對第一個比對模式執行該分支的對應運算式 (稱為例外狀況處理常式),而整體運算式會傳回該例外狀況處理常式中的運算式值。 如果沒有相符的模式,例外狀況就會向上傳播呼叫堆疊,直到找到相符的處理常式為止。 例外狀況處理常式中每個運算式傳回的值型別必須符合 try 區塊中運算式傳回的型別。

通常,發生錯誤的事實也表示每個例外狀況處理常式中的運算式沒有任何有效值傳回。 常見的模式是讓運算式的型別成為選項型別。 下列程式碼範例會說明此模式。

let divide1 x y =
   try
      Some (x / y)
   with
      | :? System.DivideByZeroException -> printfn "Division by zero!"; None

let result1 = divide1 100 0

例外狀況可能是 .NET 例外狀況,也可能是 F# 例外狀況。 您可以使用 exception 關鍵字來定義 F# 例外狀況。

您可以使用各種模式來依據例外狀況型別和其他條件進行篩選;下表摘要說明這些選項。

模式 描述
:? exception-type 比對指定的 .NET 例外狀況型別。
:? exception-type as identifier 比對指定的 .NET 例外狀況型別,但會為例外狀況提供具名值。
exception-name(arguments) 比對 F# 例外狀況型別並繫結引數。
識別碼 比對任何例外狀況,並將名稱繫結至例外狀況物件。 相當於 :?System.Exception asidentifier
identifier when condition 如果條件為 true,則比對任何例外狀況。

範例

下列程式碼範例說明如何使用各種例外處理常式模式。

// This example shows the use of the as keyword to assign a name to a
// .NET exception.
let divide2 x y =
  try
    Some( x / y )
  with
    | :? System.DivideByZeroException as ex -> printfn "Exception! %s " (ex.Message); None

// This version shows the use of a condition to branch to multiple paths
// with the same exception.
let divide3 x y flag =
  try
     x / y
  with
     | ex when flag -> printfn "TRUE: %s" (ex.ToString()); 0
     | ex when not flag -> printfn "FALSE: %s" (ex.ToString()); 1

let result2 = divide3 100 0 true

// This version shows the use of F# exceptions.
exception Error1 of string
exception Error2 of string * int

let function1 x y =
   try
      if x = y then raise (Error1("x"))
      else raise (Error2("x", 10))
   with
      | Error1(str) -> printfn "Error1 %s" str
      | Error2(str, i) -> printfn "Error2 %s %d" str i

function1 10 10
function1 9 2

注意

try...with 建構是與 try...finally 運算式不同的運算式。 因此,如果您的程式碼需要 with 區塊和 finally 區塊,您必須為這兩個運算式建立巢狀結構。

注意

您可以在非同步運算式、工作運算式和其他計算運算式中使用 try...with,在此情況下,會使用自訂版本的 try...with 運算式。 如需詳細資訊,請參閱非同步運算式工作運算式計算運算式

另請參閱