异常:引发和重新引发函数

  • raise 函数用于指示发生了错误或异常情况。 有关错误的信息是在异常对象中捕获的。
  • reraise 函数用于在调用链上传播已处理的异常。

语法

raise (expression)

注解

raise 函数生成异常对象并启动堆栈展开过程。 堆栈展开过程由公共语言运行时(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在计算列表、数组、序列或计算表达式(包括task { .. }或)async { .. }的构造块try/with上使用with函数。

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@()

另请参阅