Home
Insert
Update snippet 'Raising arbitrary exceptions with failwith-style syntax'
Title
Passcode
Description
failwith/failwithf are a useful operators, but they only raise exceptions of type SystemException. Here's a simple way to generalize them.
Source code
let gfailwith (exncons : string -> #exn) (msg : string) = exncons msg |> raise let gfailwithf (exncons : string -> #exn) fmt = Printf.ksprintf (gfailwith exncons) fmt // example open System let failwithf fmt = gfailwithf (fun msg -> new ArgumentException(msg)) fmt let rec factorial = function | n when n < 0 -> failwithf "factorial: invalid argument %d." n | 0 -> 1 | n -> n * factorial (n-1) factorial -2
Tags
exceptions
failwith
exceptions
failwith
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update