在F#中,我们可以方便地使用同时抛出Exception实例的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
但是,上面的代码会导致两个警告:
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
如何避免该警告?
答案 0 :(得分:8)
删除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