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
评论前必须登录!
注册