Custom exceptions in F#
April 29, 2017 Leave a comment
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.