14. Handling errors
In this chapter you will learn:
- how to write "this may fail" into a function signature with
throws; - how an error travels up the call chain until somebody catches it;
throw,try/catchandfinally, and the order in which they run;- error classes and the order of several
catchclauses; - how to rethrow with
throw problem, adding context to an error; - how
requirefrom@std/nullsturns "this should have had a value, but it wasnull" into an error; - which failures are not
Errors, and why you fix them instead of catching them.
14.1 Failure in the type: throws
Some operations fail: text does not parse, a file is missing, the network is down. Sprig does not use hidden exceptions; it puts failure in the signature: -> Int throws Error reads "returns an Int, or fails with an Error".
func parse_amount(text: String) -> Int throws Error:
let value = text.toIntOrNull()
if value == null:
throw Error("not a number: " + text)
return value
func total(lines: List[String]) -> Int throws Error:
var sum = 0
for line in lines:
sum += parse_amount(line)
return sum
try:
print(total(["12", "30"]))
print(total(["12", "abc"]))
catch problem: Error:
print("failed: " + problem.message)
finally:
print("done")42
failed: not a number: abc
doneThe error travels up the call chain like this:
top-level try: ← caught here
total(["12", "abc"]) ← does not handle it; its signature says throws Error too
parse_amount("abc") ← throw Error("not a number: abc")Line by line:
func parse_amount(text: String) -> Int throws Error:says in its signature that it may throw anError.text.toIntOrNull()returnsInt?;if value == null: throw Error("not a number: " + text)throws an error with a message.throwends the current path at once, and, likereturn, it narrows: after thethrow,valueis known to have a value, soreturn valueworks.totalcallsparse_amountand does not handle the error, so its signature saysthrows Errortoo. The error climbs one explicit level at a time; any level may choose to handle it or to declare it onward.try:wraps the call that may fail;catch problem: Error:catches it andproblem.messageis the text;finally:runs whether the try succeeded, failed or returned early, and may be left out.
Follow the three output lines:
| what happens | output |
|---|---|
total(["12", "30"]) returns 42 normally | 42 |
total(["12", "abc"]) throws in parse_amount; it travels up to the top level | (nothing yet) |
catch problem: Error: catches and prints the message | failed: not a number: abc |
finally: runs | done |
Top-level statements are special: they may call throwing functions without declaring anything. An error nobody catches ends the program with SPR-RUNTIME-ERROR, as 14.6 shows.
A return inside finally is allowed (it overrides the value from the try), but it easily confuses readers; do not write it.
14.2 Deliberate mistake: neither handling nor declaring
func parse_amount(text: String) -> Int throws Error:
let value = text.toIntOrNull()
if value == null:
throw Error("not a number: " + text)
return value
func show(text: String) -> Unit:
print(parse_amount(text))SPR-FLOW-THROWS [FLOW] main.spr:8:11: Call may throw Error; declare 'throws Error' or handle it with try/catch
hint: Declare it on 'show' by changing its header to 'func show(text: String) -> Unit throws Error:', and its callers then handle or declare it too (top-level statements need neither), or handle it where it happens: 'try:' around the call, then 'catch problem: Error:' with what to do instead. Sprig keeps recoverable errors explicit; there is no implicit propagation.How to read it:
- the position is the
parse_amount(text)call insideshow; - the message gives two choices: add
throws Errortoshow's signature, ortry/catchhere; - the hint spells out both fixes and reminds you that once
showdeclares it, its callers must handle or declare it too (top-level statements excepted); - the last sentence is the design: there is no implicit propagation. Read a signature and you know whether it can fail; read a call and you know where failure is handled.
14.3 Error classes
With a single Error, callers can only tell failures apart by their message text. When you need to tell them apart, define the error as a class:
# Error classes: a class with a message field, then a declaration that it follows Error.
class NotFound:
let message: String
let sku: String
conform NotFound to Error(message)
class OutOfStock:
let message: String
let missing: Int
conform OutOfStock to Error(message)
func take(sku: String, wanted: Int) -> Int throws NotFound, OutOfStock:
if sku != "A1":
throw NotFound(message="no item " + sku, sku=sku)
if wanted > 5:
throw OutOfStock(message="only 5 left", missing=wanted - 5)
return wanted
func order(sku: String, wanted: Int) -> String:
try:
return "took " + take(sku, wanted)
catch problem: NotFound:
return "unknown sku " + problem.sku
catch problem: Error:
return "problem: " + problem
print(order("A1", 2))
print(order("ZZ", 1))
print(order("A1", 9))took 2
unknown sku ZZ
problem: only 5 left- An error class is an ordinary
classwith a message field (herelet message: String) and any other fields (sku,missing). conform NotFound to Error(message)declares it anError; the parentheses name the message field. Chapter 16 explainsconform; for now, copy the shape.throws NotFound, OutOfStocklists each error it may throw;throw NotFound(message=..., sku=...)writes field names like any class construction.- You can write several
catchclauses; the first match from the top wins. So the specificNotFoundgoes before the generalError; the other way around,catch problem: Error:catches everything and the latercatch problem: NotFound:can never run — the compiler reportsSPR-FLOW-THROWSwith the messageCatch of NotFound is unreachable: Error already catches it. - Inside
catch problem: NotFound:,problemis aNotFound, soproblem.skuworks; joining the error into a string ("problem: " + problem) uses its message.
Using specific types in low-level functions and Error at the boundary is a common split.
14.4 The message field may have another name
The message field does not have to be called message. The field named in the conform parentheses is the message:
class NotFound:
let text: String
let sku: String
conform NotFound to Error(text)
func find(sku: String) -> String throws NotFound:
if sku != "A1":
throw NotFound(text="no item " + sku, sku=sku)
return "found A1"
try:
print(find("A1"))
print(find("ZZ"))
catch problem: NotFound:
print(problem.text + " / " + problem.sku)
print("joined: " + problem)
catch problem: Error:
print(problem.message)found A1
no item ZZ / ZZ
joined: no item ZZconform NotFound to Error(text)makestextthe message field, soproblem.textreads it, and"joined: " + problembuilds the same value.- The message field must be a
String:
Deliberate mistake: the message field is not a String
class Bad:
let code: Int
conform Bad to Error(code)SPR-CONFORM-TARGET [TYPE] main.spr:3:1: sprig.runtime.SprigError has no public or protected constructor taking (long) (expected (java.lang.String) | (java.lang.String, java.lang.Throwable), actual (long))
hint: Name fields whose JVM shapes match one constructor exactly, in its parameter order.code is an Int, and the compiler finds no error constructor accepting it: SPR-CONFORM-TARGET. You do not need every word: the position points at the conform line, the message says no constructor matches, and the hint tells you to use fields whose types line up. Making it a String fixes it.
14.5 Rethrowing: adding context
An error message from a low-level function is not always useful to its caller. A catch may throw a new error that carries the old message:
func parse(text: String) -> Int throws Error:
let value = text.toIntOrNull()
if value == null:
throw Error("not a number: " + text)
return value
func load(text: String) -> Int throws Error:
try:
return parse(text)
catch problem: Error:
throw Error("cannot load amount: " + problem.message)
try:
print(load("12"))
print(load("abc"))
catch problem: Error:
print("failed: " + problem.message)
finally:
print("done")12
failed: cannot load amount: not a number: abc
doneloadcallsparse; incatch problem: Error:it builds a new message,"cannot load amount: " + ..., and throws a newError.- The original error is replaced by the one with context, and
load's signature still saysthrows Error. - The first call returns 12; the second is caught at the top, which prints the new message;
finallyprintsdonelast.
The argument of throw need not be a new error: throw problem rethrows the caught error unchanged, and is valid too (the signature does not change). Wrapping exists to bring the message closer to what the caller cares about.
14.6 The bridge between null and Error: require
require(value, message) from @std/nulls returns the value when it has one and throws an Error carrying the message when it is null. It turns the surprise of "this should have had a value, but it was null" into an explicit failure:
import "@std/nulls.spr" as nulls
let stock: Map[String, Int] = {"tea": 12}
print(nulls.or_else(stock["tea"], 0))
print(nulls.or_else(stock["milk"], 0))
func port(text: String) -> Int throws Error:
return nulls.require(text.toIntOrNull(), "port must be a number: " + text)
try:
print(port("8080"))
print(port("eighty"))
catch problem: Error:
print(problem.message)12
0
8080
port must be a number: eightynulls.or_else(stock["tea"], 0)is as in the previous chapter: 12 when there is a value, 0 when"milk"is missing.port's signature is-> Int throws Error, because it callsrequire, which may throw.port("8080")returns 8080; inport("eighty"),toIntOrNull()isnull, sorequirethrowsError("port must be a number: eighty").- The top-level
catch problem: Error:catches it and printsproblem.message, which is the last line. Without thetry/catch, the program would end withSPR-RUNTIME-ERRORand print the same message.
T? or throw? A simple dividing line: a result that does not exist is normal (lookups, map misses, optional settings), so return T?; the caller passed something they should not have, or the outside world failed (a parse failure, a missing file), so throw.
14.7 Not every failure is an Error
Integer overflow and list indexes out of bounds are bugs in the program; at run time they report SPR-RUNTIME-EXCEPTION (note the [RUNTIME] tag, not [TYPE]). They are not Errors, cannot be expressed with throws Error, and catch problem: Error: does not catch them:
try:
let big = 9223372036854775807 + 1
print(big)
catch problem: Error:
print("caught")$ sprig run main.sprSPR-RUNTIME-EXCEPTION [RUNTIME] main.spr:2:5: Numeric error: Int addition overflow
hint: The exact result does not fit in the integer type. Check before the operation, for example 'if value > 0 and total > 9223372036854775807 - value:' for an Int addition, or catch it: import java.lang.ArithmeticException as ArithmeticException, then put the operation in 'try:' with 'catch problem: ArithmeticException:'. See `sprig help numerics`. Run with --stacktrace to see the JVM stack.
1 error(s); run 'sprig explain <code>' for details on a diagnostic code.catch problem: Error: did not print caught; the program ended on this diagnostic. A list index out of bounds is the same:
let items: List[Int] = [1, 2, 3]
print(items[5])SPR-RUNTIME-EXCEPTION [RUNTIME] main.spr:2:1: List index 5 is out of bounds; size is 3
hint: Check the list length before indexing. Run with --stacktrace to see the JVM stack.
1 error(s); run 'sprig explain <code>' for details on a diagnostic code.The right response to these is to fix the code: check before adding, check the length before indexing. The hint shows two roads, "check first" and "import the Java exception and catch it"; the second belongs to chapter 21.
An uncaught Error takes the other road, reported as SPR-RUNTIME-ERROR:
func parse(text: String) -> Int throws Error:
throw Error("boom: " + text)
print(parse("x"))SPR-RUNTIME-ERROR [RUNTIME] main.spr:2:5: Uncaught Error: boom: x
hint: Catch it with try/catch or declare throws in the calling function. Run with --stacktrace to see the JVM stack.
1 error(s); run 'sprig explain <code>' for details on a diagnostic code.Both diagnostics tell you: adding --stacktrace prints a JVM stack showing the compiled classes and the JVM call chain. The syntax is sprig run --stacktrace file.spr.
Coming from another language?
- There are no hidden throw paths: the signature says
throws Error, and the caller must handle or declare it. The compiler does not let you forget. - It looks like Java's checked exceptions, but Sprig has one
Errorfamily and no resource-management syntax beyondfinally(no try-with-resources, nousing). - Java's runtime exceptions (such as
ArithmeticException) are notErrors in Sprig. After importing the Java class you may writethrows ArithmeticExceptionandcatch problem: ArithmeticException:, but nobody forces you to, and a beginner does not need to.
Summary
throwsis part of the signature; callers eithertry/catchor declare it too; top-level statements may call directly, and there is no implicit propagation.throwends the current path and narrows;finallyruns no matter what.- An error class is a
classwith amessage(or any otherStringfield) plusconform X to Error(field); severalcatchclauses match top to bottom, so the specific one goes first. - A
catchmaythrowa new error orthrow problemto rethrow;nulls.requireturnsnullinto an error. - Runtime exceptions and
SPR-RUNTIME-ERRORare notErrors: fix the code rather than catching them, and use--stacktraceto see the call stack.
Exercises
Exercise 1 (parse and catch). Write parse(text: String) -> Int throws Error that throws Error("bad number: " + text) when parsing fails. Call parse("7") and parse("seven"), and print the message with try/catch.
Answer
func parse(text: String) -> Int throws Error:
let value = text.toIntOrNull()
if value == null:
throw Error("bad number: " + text)
return value
try:
print(parse("7"))
print(parse("seven"))
catch problem: Error:
print("error: " + problem.message)7
error: bad number: sevenExercise 2 (division by zero is an error, not an exception). Write divide(a: Int, b: Int) -> Int throws Error: throw Error("division by zero") when b is 0, otherwise return a.divTrunc(b). Check that 6/2 gives 3 and 6/0 is caught.
Answer
func divide(a: Int, b: Int) -> Int throws Error:
if b == 0:
throw Error("division by zero")
return a.divTrunc(b)
try:
print(divide(6, 2))
print(divide(6, 0))
catch problem: Error:
print("cannot divide: " + problem.message)3
cannot divide: division by zeroExercise 3 (an error class). Define Empty with two String fields, message and name, and conform Empty to Error(message). greeting(name) throws Empty(...) for an empty name; the caller writes catch problem: Empty: and prints the message and problem.name.
Answer
class Empty:
let message: String
let name: String
conform Empty to Error(message)
func greeting(name: String) -> String throws Empty:
if name == "":
throw Empty(message="name is empty", name=name)
return "hello " + name
try:
print(greeting("Ada"))
print(greeting(""))
catch problem: Empty:
print(problem.message + " [" + problem.name + "]")hello Ada
name is empty []Exercise 4 (rethrow). read_count fails with not a number: x. Write a load layer that wraps it with throw Error("config: " + problem.message) for the caller, then catch and print at the top.
Answer
func read_count(text: String) -> Int throws Error:
let value = text.toIntOrNull()
if value == null:
throw Error("not a number: " + text)
return value
func load(text: String) -> Int throws Error:
try:
return read_count(text)
catch problem: Error:
throw Error("config: " + problem.message)
try:
print(load("3"))
print(load("x"))
catch problem: Error:
print(problem.message)3
config: not a number: xExercise 5 (the order of finally). Write report(): the try prints working and then throw Error("boom"); catch problem: Error: prints caught: boom; finally: prints cleanup. Guess the three lines before you run it.
Answer
func report() -> Unit:
try:
print("working")
throw Error("boom")
catch problem: Error:
print("caught: " + problem.message)
finally:
print("cleanup")
report()working
caught: boom
cleanupNext chapter: Functions as values.
