Tutorial, lesson 8 of 9
When things fail
A call that fails stops the script, at its line, with the reason. float("n/a") is no number,
so a garbled reading would end the run. try in front of the call turns the failure into a
value: t, err = try float($line) gives the number and null, or, when the call fails, an
Error, with t left unset. The loop tests $err != null, says which line it skipped and why,
and goes on to the next with continue. An Error in a string prints what went wrong.
fail raises an Error of a proc’s own. read_limit fails with a kind, Error.NOT_FOUND,
when the settings have no limit, and the caller asks for that kind with error.is: a missing
limit falls back to 25, and any other Error stops the script. Write [alarms] for [alarm] and
run it: the script says “no alarm limit” and carries on.
fail "reading the settings", $err wraps toml.decode’s Error with what the proc was doing, and
fail "starting", $err wraps it again. Write limit = 23 degrees and run it: the script stops
with the whole chain, each step’s message before the one under it: ela: starting:, then
reading the settings:, then toml.decode’s own, with the line and column of the fault.
error.is finds a kind anywhere down the chain.
A proc with no return gives no value, so try on it gives the Error alone:
err = try check($line). Write ok, err = try check($line) and ela stops at that line and
says to take one name.
try catches the data’s failures, never the script’s mistakes: a key read with $m["k"] that
isn’t there stops the script even under try, which is why read_limit asks has first.
try takes a command too: err = try grep -q x notes.txt gives null, or an Error that holds
grep’s exit code, and error.is($err, 2) asks for that code, grep’s “can’t read the file”.
out, err = try $(git pull) gives the output as well. Commands don’t run in the playground.