Pat­tern match­ing is every­where in F#, you can use it in let bind­ings, in func­tion para­me­ters, in for loops, every­where, and it is totally amaz­ing. It is in my opin­ion one of the best fea­tures of F#, and in func­tional lan­guages in gen­eral, heck, Erlang goes as far as not hav­ing an assign­ment oper­a­tor and every­thing is pat­tern matched instead (yup, that’s right, ‘=’ is the pat­tern match oper­a­tor in Erlang, not assign­ment!). Once you’ve had a chance to work with it you’ll under­stand why those func­tional folks love it so much!

In terms of excep­tion han­dling, con­sider this piece of code in C#:

Notice that the switch state­ment allows you to apply the same han­dler to mul­ti­ple cases but not the catch state­ments, which leads to dupli­cated excep­tion han­dling code. Wouldn’t it be nice if you don’t have to keep repeat­ing yourself?

Now, let’s see how pat­tern match­ing in F# lets us do just that:

Pretty neat, right? Not only are you able to group han­dling code for dif­fer­ent excep­tions, you can also use wild card ( _ ) and when guards (e.g. | _ as ex when ex.Message.Contains(“Oops”) to match any excep­tion whose mes­sage con­tains the term ‘Oops’) too, which give you a very fine con­trol over which han­dler is used for what exceptions.

As the pat­terns are matched from top to bot­tom, if you move the wild­card pat­tern to the top you’ll receive a set of gen­tle warn­ings from the com­piler let­ting you know that doing so will mean that each of the sub­se­quent pat­terns will never be matched.

It’s also worth not­ing that whilst F# has try-catch and try-finally expres­sions, there is no try-catch-finally expres­sion.

Share

2 Responses to “F# — Exception handling the pattern matching way!”

  1. the wild­card isn’t even required.

    | ex -> printfn “Generic excep­tion was caught: %s” ex.Message

  2. […] against the type of the mes­sage (sim­i­lar to how you can use pat­tern match­ing in a try-with block) before pass­ing the mas­sage to the appro­pri­ate han­dler func­tion that under­stands that […]

Leave a Reply