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 =
    try
        raise (ProductNotFoundException("Book", 10, 543665))
    with
        | 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.

Advertisement

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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: