Handling .NET exceptions in F#
April 30, 2017 Leave a comment
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 = try raise (new System.IndexOutOfRangeException("Your list is not large enough")) with | 😕 System.IndexOutOfRangeException as ex -> printfn "Out of range: %s" ex.Message 0 | 😕 System.Exception as ex -> printfn "Something bad has happened: %s" ex.Message 0
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.