📜  没有尝试的F#示例

📅  最后修改于: 2021-01-01 14:41:24             🧑  作者: Mango

使用Try-With块的F#异常处理

F#提供了try-with关键字来处理异常。 Try块用于封装可疑代码。 with块用作处理程序,以处理try块引发的异常。让我们看一个例子。

let ExExample a b =
  let mutable c = 0
  try
    c <- (a/b)
  with
    | :? System.DivideByZeroException as e -> printfn "%s" e.Message
  printfn "Rest of the code"

ExExample 10 0

输出:

Attempted to divide by zero.
Rest of the code

F#最后尝试处理异常的示例

Try-Finally块用于在异常发生后释放资源。资源可以是输入,输出,内存或网络等。

let ExExample a b =
    let mutable c = 0
    try
        try
            c <- (a/b)
        with
            | :? System.DivideByZeroException as e -> printfn "%s" e.Message
    finally 
        printfn "Finally block is executed"
    printfn "Rest of the code"

ExExample 10 0

输出:

Attempted to divide by zero.
Finally block is executed
Rest of the code