14. Errors and exceptions
Things go wrong: files are missing, input is malformed, the network drops, a bug divides by zero. A good program decides, for each kind of failure, who should handle it and how. Grav gives you three tools, each for a different kind of problem:
| Kind of problem | Example | Tool |
|---|---|---|
| an expected outcome that the caller must look at | "user not found", "not a number" | a return value: Result<T, E>, Option<T> or T? |
| an unusual condition, handled somewhere up the call chain | the file vanished, the server refused | an exception: throw and try/catch |
| a bug: the program is in a state it should never be in | an impossible case, a broken invariant | a panic: panic(...) stops the program |
In this chapter you will learn:
- how to throw and catch exceptions, and
finally, - the standard exception classes, and writing your own,
- the errors the language itself raises (index out of range, division by zero, ...),
Result<T, E>for errors as values,- panics, and recovering from them in servers and threads.
Throwing and catching
throw stops the current function and hands an exception object to whoever called it, then their caller, and so on, until a try block with a matching catch handles it:
import "std"
fn divide(a: int, b: int) -> int {
if (b == 0) { throw new ValueError("cannot divide by zero") }
return a / b
}
fn main() {
try {
print(divide(10, 2))
print(divide(1, 0))
print("not reached")
} catch (e: ValueError) {
print("caught: ${e.message()}")
}
print("carrying on")
}5
caught: cannot divide by zero
carrying on- Any object can be thrown, but by convention you throw a subclass of
Exceptionfrom the standard library. catch (e: ValueError)handlesValueErrors and its subclasses. The exception object is available ase.- The rest of the
tryblock is skipped. After thecatch, the program continues after the wholetrystatement.
A try can have several catch clauses. The first one whose class matches wins, so put the specific ones first:
import "std"
fn risky(n: int) {
if (n == 1) { throw new IndexError("too far") }
if (n == 2) { throw new IOError("disk unplugged") }
throw new ValueError("bad number")
}
fn main() {
for (n in 1..=3) {
try {
risky(n)
} catch (e: IndexError) {
print("index: ${e.message()}")
} catch (e: Exception) {
print("other: ${e.describe()}")
}
}
}index: too far
other: IOError: disk unplugged
other: ValueError: bad numberA catch that can never run, because an earlier one already catches a parent class, is a compile error.
What an exception carries
Every standard exception has:
message(): the text it was created with,kind(): its kind, like"ValueError",describe():"Kind: message", which is also whatprint(e)shows.
finally
A finally block runs no matter how the try ends: normally, through a caught exception, through an exception that keeps going, or through return, break or continue. It is the place for clean-up:
import "std"
fn load(n: int) -> string {
try {
if (n < 0) { throw new ValueError("negative") }
return "loaded ${n}"
} catch (e: ValueError) {
return "error: ${e.message()}"
} finally {
print("cleanup for ${n}")
}
return ""
}
fn main() {
print(load(1))
print(load(-1))
}cleanup for 1
loaded 1
cleanup for -1
error: negativeUnlike defer (chapter 4), finally also runs when an exception passes through.
try as a value
When all a catch would do is pick a fallback value, try can be written as an expression: the value, or the fallback when working it out throws. catch alone catches any Exception; catch (e: T) only a T, and names it:
import "std"
fn main() {
let port = try Format.toInt("80a") catch 8080
let size = try Format.toInt("12") catch 0
let why = try "${Format.toInt("x")}" catch (e: ValueError) { "invalid: " + e.message() }
print("${port} ${size} ${why}")
}8080 12 invalid: 'x' is not an integerPassing an exception on
A catch can do something and then throw the same exception again, for someone further up to handle:
import "std"
fn main() {
try {
try {
throw new RuntimeError("disk full")
} catch (e: RuntimeError) {
print("logging: ${e.message()}")
throw e
} finally {
print("inner finally")
}
} catch (e: Exception) {
print("outer: ${e.describe()}")
}
}logging: disk full
inner finally
outer: RuntimeError: disk fullVariables changed inside a try keep their latest values in its catch, which helps to report how far you got:
import "std"
fn main() {
let done = 0
try {
for (s in ["4", "8", "x", "16"]) {
if (!Format.isInt(s)) { throw new ValueError("bad input '${s}'") }
done += 1
}
} catch (e: ValueError) {
print("stopped after ${done}: ${e.message()}")
}
}stopped after 2: bad input 'x'An exception that passes through functions on its way to a catch releases what those functions held: their variables are dropped as if each function had returned, so their objects are destroyed and nothing leaks. A constructor that throws frees its half-built object; its destructor does not run, because the object never finished being built.
Uncaught exceptions
An exception that nobody catches ends the program. It prints the exception and where it was thrown, and exits with status 1:
grav: uncaught exception: ValueError: cannot divide by zero
stack trace (most recent call last):
at main (app.grav:9)
at divide (app.grav:4)Builds made with --release or --no-trace leave the stack trace out, which makes them a little faster.
The standard exceptions
| Class | Means |
|---|---|
Exception | the base of them all; catch it to catch everything |
ValueError | an argument or input is unsuitable |
TypeError | a value has the wrong type (for example a failed as) |
IndexError | an index is out of range |
ArithmeticError | integer division or % by zero |
StateError | the operation does not fit the current state (popping an empty stack, x! on null) |
NotFound | something looked up does not exist |
IOError | a file, network or process operation failed |
TimeoutError | something took too long |
RuntimeError | anything else |
The standard library throws these when it is misused, and the language throws some itself when the standard library is loaded:
import "std"
fn main() {
let xs = new Array<int>()
try { print(xs[3]) } catch (e: IndexError) { print(e.describe()) }
let fixed = [1, 2, 3]
let i = 7
try { print(fixed[i]) } catch (e: IndexError) { print(e.describe()) }
let zero = 0
try { print(10 / zero) } catch (e: ArithmeticError) { print(e.describe()) }
let empty = new Stack<int>()
try { empty.pop() } catch (e: StateError) { print(e.describe()) }
}IndexError: Array index 3 out of range (length 0)
IndexError: array index 7 out of range (length 3)
ArithmeticError: integer division by zero
StateError: Stack.pop on an empty stackWithout import "std", these checks still happen, but they panic instead of throwing, because the exception classes are not there.
Your own exceptions
Extend Exception to create your own kinds of errors. A hierarchy lets callers catch a whole family at once:
import "std"
class AppError extends Exception {
constructor(m: string) { super(m) }
fn kind() -> string { return "AppError" }
}
class NotAllowed extends AppError {
public user: string
constructor(user: string) {
super("${user} may not do that")
self.user = user
}
fn kind() -> string { return "NotAllowed" }
}
fn check(user: string) {
if (user != "admin") { throw new NotAllowed(user) }
}
fn main() {
try {
check("guest")
} catch (e: AppError) {
print(e.describe())
}
}NotAllowed: guest may not do thatFields like user let the handler get at the details without parsing the message.
Errors as values: Result
Exceptions are easy to ignore: nothing in fn parse(s: string) -> int tells the caller it might throw. When failure is a normal, expected outcome, return it instead. Result<T, E> is a data enum that holds either Ok(value) or Err(error):
import "std"
fn parseAge(s: string) -> Result<int, string> {
if (s == "") { return Result.Err("empty input") }
if (!Format.isInt(s)) { return Result.Err("not a number: " + s) }
let n = Format.toInt(s)
if (n < 0 || n > 150) { return Result.Err("out of range: ${n}") }
return Result.Ok(n)
}
fn main() {
for (input in ["42", "", "abc", "200"]) {
match (parseAge(input)) {
case Ok(age): print("age ${age}")
case Err(msg): print("error: ${msg}")
}
}
print(parseAge("x").unwrapOr(0))
print(parseAge("20").map(fn(n: int) => n + 1))
}age 42
error: empty input
error: not a number: abc
error: out of range: 200
0
Ok(21)The return type now says "this can fail, and here is what you get when it does". The caller has to look inside the Result to get the value, so the error cannot be ignored by accident.
Useful methods (see Result for all of them):
| Method | Gives |
|---|---|
isOk(), isErr() | which one it is |
unwrap() | the value, or throws StateError on an Err |
unwrapOr(fallback) | the value, or the fallback |
map(f) | Ok(f(value)), passing errors through |
mapErr(f) | Err(f(error)), passing values through |
andThen(f) | chains another step that can fail |
Choosing between them
- Use
Result(orT?/Option) when the caller is expected to handle the failure right away: parsing, validation, lookups. - Use exceptions when failure is rare and is best handled far away from where it happens: a request handler catching any
IOErrorfrom deep inside. - Use panics for bugs, which should not be "handled" at all, only fixed.
Panics
A panic means the program has hit a bug. The usual response is to stop at once, with a message and the call stack, before the bug does more damage:
panic("message")panics on purpose, for "this cannot happen" situations.assert(condition, "message")panics when the condition is false.- Using a field or method through
null, and runaway recursion (a stack overflow), panic too.
A catch never catches a panic. That is deliberate: a panic is not an error condition to handle, it is a sign that the program's own logic is wrong.
Recovering from panics
A server should not stop serving everyone because one request hit a bug. Inside a recovery point, a panic is turned into a recoverable failure instead: it unwinds the stack like an exception that no catch can catch, finally blocks run (so locks are released), and the recovery point receives the message.
Panic.recover(body) runs a function as a recovery point. It returns "" if the function finished, or the panic's message:
import "std"
fn main() {
let failure = Panic.recover(fn() {
try {
panic("the ledger does not balance")
} catch (e: Exception) {
print("not reached: a catch never takes a panic")
} finally {
print("finally still runs")
}
})
print("recovered: " + failure)
let missing: Result<int, string> = Result.Err("no such user")
print(Panic.recover(fn() { missing.unwrap() }))
print("still running")
}finally still runs
recovered: panic: the ledger does not balance
uncaught exception: StateError: called unwrap() on Err(no such user)
still runningAn exception that escapes a recovery point is stopped there too.
Some recovery points are built in:
- Every
HttpServerrequest. A panicking handler answers500 internal error, the panic is logged, and the server keeps serving. - Every
Threadbody.join()reports the panic instead of the whole program stopping.
Recovery can be switched off, globally with Panic.setRecovery(false) or the environment variable GRAV_PANIC_RECOVERY=off, or per thread with Panic.setThreadRecovery(false). Then a panic stops the program even inside a recovery point, which is handy while debugging. See Panic.
Summary
throw new SomeError("...")raises an exception;try/catch (e: Type)handles it;finallyalways runs.- Catch specific classes first;
Exceptioncatches everything. - The standard library and the language throw
IndexError,ArithmeticError,StateErrorand others; extendExceptionfor your own. Result<T, E>returns failure as a value the caller must look at.panicandassertare for bugs;Panic.recover, servers and threads can recover from them.
Exercises
- Write
fn readPositive(s: string) -> intthat throws aValueErrorfor bad input, and a loop that asks for numbers in an array of strings, reporting the bad ones and summing the good ones. - Rewrite exercise 1 with
Result<int, string>. Which version do you prefer for this job, and why? - Make a hierarchy
BankError→InsufficientFunds,AccountLocked, and awithdrawmethod that throws them. CatchBankErrorin one place. - Use
finallyto print "done" after a loop that may throw halfway. - Write a function that panics on a "can't happen" case, and call it inside
Panic.recover. Then setGRAV_PANIC_RECOVERY=offand run it again.
Next: Memory →