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