14 When Things Go Wrong
A correct program can still meet things that go wrong: a line that
should hold a number holds a word, a divisor turns out to be zero, a
file is not there. Zeno calls these errors, and gives a program
three words to deal with them: raise to say that something
has gone wrong, try and except to deal with
it, and raises to say in a function’s heading what it may
raise.
14.1 Bugs and errors
Zeno draws a line between two kinds of thing that go wrong.
A bug is a mistake in the program itself: a misspelt name,
"abc" - 1, calling something that is not a function. The
checker finds almost all of them before the program runs, and the
program does not start until they are fixed.
An error is something that can go wrong in a correct program: bad input, a division by a value that turned out to be zero, a position that came from outside. These happen while the program runs, and the program can catch them and carry on.
Catching a bug hides it. A program that catches "this name does not exist" and carries on has a mistake in it that nobody will ever see. Since the checker reports bugs before the program runs, there is nothing of that kind left to catch. (Decision 4.1.)
14.2 An error that is not caught
An error that nothing catches stops the program, with its kind, its message and the line it came from:
let readings = [20.5, 21.0]
print(readings[2])error: uncaught IndexError: index 2 is out of range for a list of length 2
--> main.zeno:2:7
|
2 | print(readings[2])
| ^
Here IndexError is the kind of error, and the
rest is its message. Every error has both.
14.3 try and except
Code that may raise an error goes in a try block. If an
error is raised inside it, the rest of the block is skipped, and the
except that names its kind runs instead:
for text in ["40", "fast", "7"] {
try {
let speed = int(text)
print("speed", speed)
} except ValueError {
print("not a number:", text)
}
}speed 40
not a number: fast
speed 7
If nothing is raised, the except block does not run at
all.
except Kind as e gives the error a name.
e.message is its message and e.kind the name
of its kind:
try {
print(int("fast"))
} except ValueError as e {
print(e.kind, "says:", e.message)
}ValueError says: cannot turn "fast" into an int
A try can have several excepts. The first
that fits is the one that runs:
function show(xs: list[int], at: int, by: int) {
try {
print(xs[at] // by)
} except IndexError as e {
print("position:", e.message)
} except ZeroDivisionError {
print("cannot divide by zero")
}
}
show([10, 20], 1, 5)
show([10, 20], 9, 5)
show([10, 20], 0, 0)4
position: index 9 is out of range for a list of length 2
cannot divide by zero
An error that no except names goes on as if the
try were not there, up to whoever called this code, and so
on until something catches it or the program stops.
14.4 The kinds of error
The kinds that Zeno itself raises are these:
| Kind | Raised when |
|---|---|
ValueError |
a value is the right type but cannot be
used: int("fast"), 2 ** -1 |
IndexError |
a position is outside a list or a text |
KeyError |
a dict has no such key |
ZeroDivisionError |
a number is divided by zero |
OverflowError |
a whole number is too big for its type |
FileError |
a file cannot be read or written |
Error |
anything else; and
except Error catches every kind |
except Error catches any error at all, which is useful
at the very top of a program, to report what went wrong and stop
tidily:
let big = 9223372036854775807
try {
print(big + 1)
} except Error as e {
print("stopped:", e.kind, e.message)
}stopped: OverflowError the result is too big for an int
Appendix F lists every message that the library and the runtime give.
14.5 raise
A program raises an error of its own with raise and the
kind, with a message that says what went wrong:
function check_speed(speed: int) -> int raises ValueError {
if speed < 0 or speed > 100 {
raise ValueError(f"a speed is 0 to 100, and {speed} is not")
}
return speed
}
for s in [40, 250] {
try {
print("set to", check_speed(s))
} except ValueError as e {
print(e.message)
}
}set to 40
a speed is 0 to 100, and 250 is not
A message is for the person who reads it when something goes wrong. The best ones say what was expected and what was found, as Zeno’s own messages do.
Only an error can be raised, not a piece of text:
raise "something went wrong"error: only an error can be raised, and this is str
--> main.zeno:1:1
|
1 | raise "something went wrong"
| ^
1 error found. Nothing was run.
Raising again
An except block that cannot fully deal with an error can
do what it can, then raise the same error again, so that the caller sees
it:
try {
print(int("fast"))
} except ValueError as e {
print("noted:", e.message)
raise e
}noted: cannot turn "fast" into an int
error: uncaught ValueError: cannot turn "fast" into an int
--> main.zeno:5:5
|
5 | raise e
| ^
14.6 raises: what a function may raise
raises after a function’s heading lists the errors it
may raise, so that whoever calls it can see them without reading the
body:
function read_volts(text: str) -> float raises ValueError {
return float(text)
}
print(read_volts("3.3"))3.3
It follows the rule of every type in Zeno: it can be left out, and then Zeno works it out from the body and passes it on to callers. When it is written, it must be complete. A function that says what it raises and then leaves something out is told so:
function read_volts(text: str) -> float raises KeyError {
return float(text)
}error: `read_volts` can raise ValueError here but does not say so. Add `raises ValueError` to it, or catch the error
--> main.zeno:2:12
|
2 | return float(text)
| ^
1 error found. Nothing was run.
In strict mode (--strict, Types, Written and Worked Out), as in
every compiled program, it must always be written, so that every heading
is a complete promise:
function read_volts(text: str) -> float {
return float(text)
}
print(read_volts("3.3"))$ zeno check --strict main.zeno
error: `read_volts` can raise ValueError here but does not say so. Add `raises ValueError` to it, or catch the error
--> main.zeno:2:12
|
2 | return float(text)
| ^
1 error found. Nothing was run.
What counts
Only errors raised on purpose must be listed: a
raise, a call to a function that raises, and
int() or float() on text, which fail on bad
input. The errors that operators raise, such as dividing by zero, a
position out of range or an overflow, can be caught, but need not be
listed.
A division or an index can fail on almost any line. If those had to
be listed, nearly every function would say
raises ZeroDivisionError, IndexError , and a label that is
on everything tells nobody anything. Java’s checked exceptions are
widely disliked for exactly that. (Decision 1.17.)
14.7 An error that carries more
An error often needs to carry more than a message: how long was waited, which pin, what code a device sent back. An object of any class can be raised, with whatever fields it needs:
class Timeout {
after_ms: int
device: str
}
function wait_for(device: str) raises Timeout {
raise Timeout(30, device)
}
try {
wait_for("sensor")
} except Timeout as t {
print("gave up on", t.device, "after", t.after_ms, "ms")
}gave up on sensor after 30 ms
except Error as e catches such an object too. Then
e.kind is the class’s name, and e.message is
the object as text:
class Timeout {
after_ms: int
}
try {
raise Timeout(30)
} except Error as e {
print(e.kind, "/", e.message)
}Timeout / Timeout(after_ms=30)
A class already means "these named values, together", so there is no second way to declare an error. (Decision 1.17.)
14.8 What is not here
Zeno has no finally. Code that must run whether or not
an error was raised is written after the try, with an
except that catches what must be caught.
On a microcontroller, a compiled program can carry its errors as plain values instead, with no jumps at all, as firmware coding standards require. Nothing in the program changes for that; it is a choice made when building, and Firmware explains it.
They are not C++ exceptions: there are no unwinding tables, and code
that does not use try pays nothing for it. (Decisions 1.17
and 5.5i.)
A bug is found before the program runs; an error happens while it
runs. raise Kind("message") raises an error, and
try { } except Kind as e { } catches it, with
e.kind and e.message.
except Error catches every kind. An object of any class can
be raised. raises lists what a function raises on purpose:
worked out when left out, complete when written, and always written in
strict mode.
Write a loop that asks for numbers with
input()until it is given one thatintaccepts.Write
function percent(part: int, whole: int) -> floatthat raises aValueErrorwith a clear message whenwholeis 0, and catch it.Make a class
SensorFaultwith a pin and a code, raise it from a function, and catch it once by its own name and once asError.Remove
raises ValueErrorfromcheck_speedand runzeno check --strict. Then writeraises KeyErrorinstead. What does each message ask for?