Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# compiler warning FS0067 for exceptions with when guards

Tags:

f#

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?

like image 364
Wallace Kelly Avatar asked Jan 01 '23 21:01

Wallace Kelly


1 Answers

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
like image 90
Wallace Kelly Avatar answered May 10 '23 05:05

Wallace Kelly