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

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

let ExExample a b =let mutable c = 0tryc < - (a/b)with| :? System.DivideByZeroException as e -> printfn "%s" e.Messageprintfn "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 = 0trytryc < - (a/b)with| :? System.DivideByZeroException as e -> printfn "%s" e.Messagefinally printfn "Finally block is executed"printfn "Rest of the code"ExExample 10 0

【使用Try-With块的F#异常处理】输出:
Attempted to divide by zero.Finally block is executedRest of the code

    推荐阅读