From 38c49a703ff9195899f2d4a56b4615b140d53dea Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sat, 5 Mar 2022 22:15:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=95=E5=8F=91=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Basic-practice-of-FSharp.fsproj | 1 + Basic-practice-of-FSharp/ExceptionThrowing.fs | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 Basic-practice-of-FSharp/ExceptionThrowing.fs diff --git a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj index 6645244..8f859eb 100644 --- a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj +++ b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj @@ -18,5 +18,6 @@ + \ No newline at end of file diff --git a/Basic-practice-of-FSharp/ExceptionThrowing.fs b/Basic-practice-of-FSharp/ExceptionThrowing.fs new file mode 100644 index 0000000..1001d01 --- /dev/null +++ b/Basic-practice-of-FSharp/ExceptionThrowing.fs @@ -0,0 +1,43 @@ +module ExceptionThrowing + +open System +// 异常引发 + +// 创建异常类型 +exception ErrorMessage of string +// 使用exception关键字创建异常类型实际上是继承自System.Exception的新类型 + +try // 使用try捕获异常 + Some (10 / 0) +with // 使用 with匹配异常信息,按顺序挨个匹配代码块中的每个模式 + | :? DivideByZeroException -> printfn "除数不能为0"; None +|> ignore // 忽略值, try with也是表达式 + +// 异常可以是.NET异常,也可以是F#异常,同样可以是自定义异常 + +let div x y = + try + if y = 0 then + raise (ErrorMessage ("除数不能为0")) // 使用raise函数将引发异常,形如C#的throw + else + raise (ErrorMessage ("没啥问题")) + with + | ErrorMessage (e) -> printfn "%s" e + +div 10 0 + +try + try // 使用try捕获异常 + Some (10 / 0) + with // 使用 with匹配异常信息 + | :? DivideByZeroException -> printfn "除数不能为0"; None + |> ignore +finally + printfn "不管发生什么都会执行" + +// 不管是否引发异常,finally都将执行 +// try with与try finally是相互独立的表达式 +// 如果需要with与finally代码块,请嵌套使用 + +// reraise函数可重新引发异常 +// failwith函数可引发F#异常,生成的异常是System.Exception类型 \ No newline at end of file