Failwith. Special operators, like failwith and invalidArg, are available in the F# language. These create exceptions that enter into an alternate control flow.
Understanding failure. In F# we do not have the same try, catch and throw syntax. Instead, we can use failwith to "throw" an exception.
First example. Here we introduce a function called validLength. This function returns true if the argument is 1 or 2, but uses failwith in all other cases.
Start We call validLength with an argument of 2. We get a result of "true" and use printfn to display this.
Next We use an argument of 200 and failwith is reached. This terminates the program with an unhandled exception.
// This function tests its argument.// ... If 1 or 2, it returns true.// Otherwise it uses a failwith command.
let validLength v =
match v with
| 1 | 2 -> true
| _ -> failwith "Length not valid"// This prints true.
let result1 = validLength 2
printfn "%A" result1
// This fails.
let result2 = validLength 200
printfn "%A" result2true
Unhandled Exception: System.Exception: Length not valid
at Microsoft.FSharp.Core.Operators.FailWith[T](String message)
at Program.validLength(Int32 v)...
at <StartupCode$ConsoleApplication3>.$Program.main@()...
Try, raise. Here we use the try and raise keywords. With try, we enter into a protected region of code—exceptions may be thrown, but we can recover.
Info The raise statement creates a NotImplementedException with a custom message. The try-block is stopped.
Note The with statement matches the NotImplementedException type. In response it prints a special message. The program does not terminate.
open System
try
// Raise a special exception.
raise (NotImplementedException "Not ready")
with
| :? NotImplementedException -> printfn "Not implemented, ignoring"Not implemented, ignoring
Finally. This block always runs. We can place some recovery logic in a finally block. If an exception is thrown, we will still enter the finally afterwards.
try
// An error occurs.
failwith "Not valid"
finally
// A finally block always runs, so we can try to recover.
printfn "Can recover here"Unhandled Exception: System.Exception: Not valid
at Microsoft.FSharp.Core.Operators.FailWith[T](String message)...
Can recover here
A review. Exception handling is powerful. With it we access a separate control flow, one that can trap and fix known problems. But some things we cannot recover from.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.