📅  最后修改于: 2021-01-01 14:41:24             🧑  作者: Mango
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
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