个性化阅读
专注于IT技术分析

使用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
赞(0)
未经允许不得转载:srcmini » 使用Try-With块的F#异常处理

评论 抢沙发

评论前必须登录!