Handling .NET exceptions in F#

When working with .NET languages from F# it can happen that the F# code needs to deal with .NET exceptions from the System namespace. The way to deal with those exceptions is about the same as in the case of F# exceptions but pattern matching in the with clause is slightly different:

let testDotNetExceptions =
        raise (new System.IndexOutOfRangeException("Your list is not large enough"))
        | 😕 System.IndexOutOfRangeException as ex ->
            printfn "Out of range: %s" ex.Message
        | 😕 System.Exception as ex ->
            printfn "Something bad has happened: %s" ex.Message

We use the type test operator 😕 which returns true if the value matches the specified type. We raise an IndexOutOfRangeException and there’s a specific exception handling block for that in the with clause. The with clause also includes a general block to catch all types of exceptions. Running the above function will produce the following output:

Out of range: Your list is not large enough

If we raise a different kind of exception…:

//raise (new System.IndexOutOfRangeException("Your list is not large enough"))
raise (new System.InsufficientMemoryException("You should increase your RAM"))

…then pattern matching in the with clause will be true for the generic exception handling block and we’ll see the following output:

Something bad has happened: You should increase your RAM

View all F# related articles here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: