In F#, we can conveniently use failwith
and failwithf
, which both throw Exception instances. Consequently, you may occasionally need to use a "when guard" to differentiate between different exception conditions.
Here is an illustrative example:
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
The above code, however, results in two warnings:
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
How do I avoid that warning?
Remove the type test pattern for the Exception
class. It is unnecessary.
with
| :? DivideByZeroException -> printfn "You divided by zero."
| ex when ex.Message.Contains("Wednesdays") -> printfn "I said, %s" ex.Message
| ex -> printfn "%s" ex.Message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With