在F#中,我们可以方便地使用failwith
和failwithf
抛出异常实例.因此,您可能偶尔需要使用"守卫时"来区分不同的异常情况.
这是一个说明性的例子:
try
let isWednesday = DateTime.Now.DayOfWeek = DayOfWeek.Wednesday
if isWednesday then failwith "Do not run this on Wednesdays!"
with
| :? DivideByZeroException -> printfn "You divided by zero."
| :? Exception as ex when ex.Message.Contains("Wednesdays") -> printfn "I said, %s" ex.Message
| ex -> printfn "%s" ex.Message
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码会产生两个警告:
Program.fs(14,7): warning FS0067: This type test or downcast will always hold
Program.fs(14,7): warning FS0067: This type test or downcast will always hold
Run Code Online (Sandbox Code Playgroud)
我该如何避免这种警告?
删除类的类型测试模式Exception
.这是不必要的.
with
| :? DivideByZeroException -> printfn "You divided by zero."
| ex when ex.Message.Contains("Wednesdays") -> printfn "I said, %s" ex.Message
| ex -> printfn "%s" ex.Message
Run Code Online (Sandbox Code Playgroud)