F# — Exception handling the pattern matching way!

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 total­ly amaz­ing. It is in my opin­ion one of the best fea­tures of F#, and in func­tion­al lan­guages in gen­er­al, 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­tion­al folks love it so much!

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

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

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

Pret­ty 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 excep­tions.

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­pil­er let­ting you know that doing so will mean that each of the sub­se­quent pat­terns will nev­er be matched.

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

Liked this post? Why not support me on Patreon and help me get rid of the ads!