typestar

Exceptions in F#

try/with catches by pattern; failwith raises with a message.

// try/with catches by pattern; failwith raises with a message.
let openHive name =
    if name = "Thistle" then failwith "wax-sealed shut"
    sprintf "%s open for inspection" name

let attempt name =
    try
        openHive name
    with
    | Failure reason -> sprintf "%s stays closed: %s" name reason

["Willow"; "Thistle"] |> List.iter (attempt >> printfn "%s")

// invalidArg carries the parameter name with the complaint.
let frames n = if n < 0 then invalidArg "n" "negative frames" else n
printfn "Frames checked: %d" (frames 9)

How it works

  1. failwith throws a Failure carrying its string.
  2. with | Failure reason -> pattern-matches the catch.
  3. invalidArg names the offending parameter.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
511
Tokens
89
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 3 in Signatures & laziness, step 22 of 27 in Language basics.

← Previous Next →

Exceptions in other languages