Basic exception handling in F#
April 23, 2017 Leave a comment
F# has a similar exception handling mechanism like in C# or Java. The most straightforward way to raise an F# exception is by way of the built-in “failwith” function which accepts an exception message:
failwith "This won't work"
Most popular OOP languages come with the try-catch-finally construct to handle exceptions. In F# it is try-with-finally. Let’s look at try-with first:
let basicExceptionRaise = try failwith "This won't work" with | Failure message -> printfn "Exception caught: %s" message
The with clause includes pattern matching where Failure will match every exception type. Therefore it’s equivalent of…
catch (Exception ex) { }
…in C#. The Failure object has a message property that can be extracted in the with clause. If we run the above function we’ll see “This won’t work” printed in the standard output.
The finally block is used so that a piece of code runs even if there was an exception. It is most often used to clean up resources such as open files or database connections. In F# try-with cannot be mixed directly with finally so the following syntax is incorrect:
let basicExceptionRaise = try failwith "This won't work" with | Failure message -> printfn "Exception caught: %s" message finally printfn "Running the finally block now"
This will result in a compilation error:
Unexpected keyword ‘finally’ in binding. Expected incomplete structured construct at or before this point or other token
Instead, we’ll need two try blocks as follows:
let basicExceptionRaise = try try failwith "This won't work" finally printfn "Running the finally block now" with | Failure message -> printfn "Exception caught: %s" message
The finally block will be executed first, here’s the output:
Running the finally block now
Exception caught: This won’t work
We can change the order of the finally and with blocks:
let basicExceptionRaise = try try failwith "This won't work" with | Failure message -> printfn "Exception caught: %s" message finally printfn "Running the finally block now"
…which will result in the with and finally blocks to be executed in a different order:
Exception caught: This won’t work
Running the finally block now
View all F# related articles here.