Error sum
Some functions can fail in more than one unrelated way. Reading a percentage can find a character that is not a digit, or a perfectly good number that is bigger than 100. Those are two different error types, and the throws clause can name both.
Two errors in one clause
The two errors are separate structs, each with its own details:
struct DigitError {
position: uint;
}
struct RangeError {
value: int;
limit: int;
}
ParsePercent names both after throws:
func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError {
A | B is a sum: one value that is an A or a B, and knows which. Sums have a part of their own, Sum types, straight after this one; here you need only what it means after throws. The order does not matter — RangeError | DigitError is the same type. No parentheses are needed: the error is the whole type after throws, so the | belongs to it.
Widening needs no code
The surprise is how little the function body has to do:
let value = try ParseNumber(text);
if value > 100 {
throw RangeError { value: value, limit: 100 };
}
return value;
ParseNumber throws a plain DigitError, yet try passes it on unchanged — a DigitError fits into the wider sum on its own. throw RangeError { ... } needs no wrapping either. This is called widening: a narrower error always fits into a sum that includes it.
flowchart LR
d["`ParseNumber` throws<br/>a `DigitError`"] -- "`try`" --> sum["`ParsePercent` throws<br/>`DigitError | RangeError`"]
r["`throw RangeError { ... }`"] --> sum
sum --> m{"The caller's `catch`"}
m -- "`e: DigitError`" --> a["`no digit at position …`"]
m -- "`e: RangeError`" --> b["`… is over 100`"]Telling the members apart
The caller tells the members apart with a typed pattern. e: DigitError matches only that member and binds it as a plain DigitError, so its fields are right there:
try {
let percent = ParsePercent(text);
PrintLine("{:5} -> {}%", text, percent);
} catch {
e: DigitError => PrintLine("{:5} -> no digit at position {}", text, e.position),
e: RangeError => PrintLine("{:5} -> {} is over {}", text, e.value, e.limit)
}
The arms must cover every member of the sum, or the compiler names the missing one.
A sum or a variant?
Error variant solved a similar problem with one type and several cases. Both work; they suit different situations.
Error sum A | B | Error variant | |
|---|---|---|
| The errors are | separate types that already exist | cases you declare together |
Passing one on with try | widens on its own | needs a mapping into a case |
| Adding a new kind of error | changes every signature that lists the sum | one new case in one declaration |
| Best for | combining errors from different places | a stable, named set of failures |
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// Some functions can fail in more than one unrelated way. Reading a percentage
// can find a character that is not a digit, or a perfectly good number that
// is bigger than 100. Those are two different error types, and the `throws`
// clause can name both:
//
// func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError
//
// `A | B` is a sum: one value that is an `A` or a `B`, and knows which. The
// order does not matter — `RangeError | DigitError` is the same type.
//
// The surprise is how little the function body has to do. A `DigitError`
// fits into the wider sum on its own, so `try ParseNumber(text)` passes it on
// unchanged and `throw RangeError { ... }` needs no wrapping either. This is
// called widening: a narrower error always fits into a sum that includes it.
import Io::PrintLine;
struct DigitError {
position: uint;
}
struct RangeError {
value: int;
limit: int;
}
func ParseNumber(text: char8[..]) -> int throws DigitError {
var total = 0;
for i in 0..text.length {
let byte = text[i];
if byte < c8'0' || byte > c8'9' {
throw DigitError { position: i };
}
total = total * 10 + ((byte as int) - 48);
}
return total;
}
func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError {
// A `DigitError` widens into the sum as `try` passes it on.
let value = try ParseNumber(text);
if value > 100 {
throw RangeError { value: value, limit: 100 };
}
return value;
}
// The caller tells the members apart with a typed pattern: `e: DigitError`
// matches only that member and binds it as a plain `DigitError`. The arms
// must cover every member of the sum, or the compiler names the missing one.
// Drop the `RangeError` arm and it says "match on 'DigitError | RangeError'
// is not exhaustive; missing _: RangeError".
func Show(text: char8[..]) {
try {
let percent = ParsePercent(text);
PrintLine("{:5} -> {}%", text, percent);
} catch {
e: DigitError => PrintLine("{:5} -> no digit at position {}", text, e.position),
e: RangeError => PrintLine("{:5} -> {} is over {}", text, e.value, e.limit)
}
}
func Main() -> int {
Show("75");
Show("7%");
Show("250");
return 0;
}
Run it
cd Examples/Errors/ErrorSum
rux run
75 -> 75%
7% -> no digit at position 1
250 -> 250 is over 100
Common mistakes
Try it yourself
- Add
Show("100");andShow("101");and predict both lines. Show("")prints0%. Add anEmptyErrorstruct, put it in the sum, and throw it on empty text. What else does the compiler ask you to change?- Swap the order of the members in the signature to
RangeError | DigitErrorand check that nothing else has to change.
Learn more
- Sum types — the next part, all about
A | B - Typed pattern —
e: DigitErrorin detail - Sum widening — when a narrower type fits a wider sum
- Error types in the Rux Reference
9.10 Error mapping
Pass an error to the caller as your own error type with try call catch { e => throw Mapped(e) }, adding context such as a line number.
9.12 Fallible main
Declare func Main() throws E (or func Main() -> int throws E) so plain try works at the top level, and see that an error ends the program with exit status 1 without printing anything.