Custom exceptions in F#

We can build custom exceptions in F# with the exception keyword. We can also assign multiple parameters to it in a tuple:

exception ProductNotFoundException of string * int * int

We can raise a custom exception with the raise function. The with clause will have a pattern matching section where we can decide what to do with the various exception types:

let customExceptionRaise =
        raise (ProductNotFoundException("Book", 10, 543665))
        | ProductNotFoundException(productName, quantity, id) ->
            printfn "We don't have %d pieces of product name %s id %d" quantity productName id

Executing this function will produce the following output:

We don’t have 10 pieces of product name Book id 543665

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: Logo

You are commenting using your 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: