Special operators, like failwith
and invalidArg
, are available in the F# language. These create exceptions that enter into an alternate control flow.
In F# we do not have the same try, catch and throw syntax. Instead, we can use failwith
to "throw" an exception.
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.
validLength
with an argument of 2. We get a result of "true" and use printfn
to display this.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@()...
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.
NotImplementedException
with a custom message. The try
-block is stopped.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
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
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.