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
failwiththrows a Failure carrying its string.with | Failure reason ->pattern-matches the catch.invalidArgnames the offending parameter.
Keywords and builtins used here
elseifletthentrywith
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.
Step 1 of 3 in Signatures & laziness, step 22 of 27 in Language basics.