F# Failwith: Exception HandlingHandle exceptions and use the failwith and raise operators. Use failwith inside match.
Failwith. A siren rings in the night sky. The air is cold. Things seem ominous. With F# we deal with errors in a rational way: we fail with them.
Special operators, like failwith and invalidArg, are available in this language. These create exceptions that enter into an alternate control flow.
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.
Match: First we call validLength with an argument of 2. We get a result of "true" and use printfn to display this.
Exception: Next we use an argument of 200 and failwith is reached. This terminates the program with an unhandled exception.
F# program that uses failwith
// 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" result2
Unhandled Exception: System.Exception: Length not valid
at Microsoft.FSharp.Core.Operators.FailWith[T](String message)
at Program.validLength(Int32 v)...
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.
Raise: This statement creates a NotImplementedException with a custom message. The try-block is stopped.
With: The with statement matches the NotImplementedException type. In response it prints a special message. The program does not terminate.
F# program that uses try with, raise
// Raise a special exception.
raise (NotImplementedException "Not ready")
| :? 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.
F# program that uses finally
// An error occurs.
failwith "Not valid"
// 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.