C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Output
true
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@()...
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
open System
try
// Raise a special exception.
raise (NotImplementedException "Not ready")
with
| :? NotImplementedException -> printfn "Not implemented, ignoring"
Output
Not implemented, ignoring
F# program that uses finally
try
// An error occurs.
failwith "Not valid"
finally
// A finally block always runs, so we can try to recover.
printfn "Can recover here"
Output
Unhandled Exception: System.Exception: Not valid
at Microsoft.FSharp.Core.Operators.FailWith[T](String message)...
Can recover here