Passing Errors On
Often the function that receives an error is not the one that should decide what it means. try before a throwing call passes the error on: on success the call is its success value and evaluation carries on; on failure the error goes to the innermost handler around the call or, with none, out of the enclosing function through its throws channel.
try-expr = "try" expr
Marking throw sites
func ParseNumber(text: char8[..]) -> int throws DigitError {
var value = 0;
for i in 0..text.length {
let c = text[i];
if c < c8'0' || c > c8'9' {
throw DigitError { position: i };
}
value = value * 10 + ((c - c8'0') as int);
}
return value;
}
func Area(width: char8[..], height: char8[..]) -> int throws DigitError {
return try ParseNumber(width) * ParseNumber(height);
}
flowchart LR
step["`try ParseNumber(width)`"] --> q{"Did it throw?"}
q -- "no" --> go["the call is its success;<br/>`Area` carries on"]
q -- "yes" --> out["`Area` throws<br/>the same error"]A throw site is a call of a function, method, constructor, operator or interface requirement that declares throws, or a call through a function value whose type does; throw is one too, but needs no mark. Every throw site is covered by a try, and an unmarked one is an error:
error: call to 'ParseNumber' can throw 'DigitError' but is not marked with 'try'
help: write 'try' before the expression
So an error can never leave through a call the reader cannot see, and can never be stored, ignored or matched by accident. A try that covers no throw site is a warning, warning: 'try' has no call that can throw.
- Evaluation runs from left to right, and stops at the first throw site that fails: nothing to its right runs. In
Area, a badwidthmeans the secondParseNumberis never called. - Leaving through
tryis an ordinary return: the error is captured first, then deferred statements run in reverse order and live locals are destroyed — including the completed fields of an aggregate whose construction the error interrupted. - A throwing call evaluates to its success, so a chain continues on it:
try MakeCounter().Doubled()callsDoubledon the counter.
Where try goes
try has the lowest precedence of any operator, so one try covers the whole expression to its right, and marks every throw site in it:
| Write | Marks |
|---|---|
try ReadDigit(t) * 10 + ReadDigit(u) | both calls |
let x = try A().B(); | both A and B |
total = try Next(); | the call — try starts the assigned value |
(try? F()) ?? fallback | only F — the parentheses are required |
try is written where an expression starts — a statement, an initializer, the value of an assignment, an argument, a return value — and never to the right of another operator:
error: 'try' cannot appear to the right of an operator
help: write 'try' at the start of the whole expression, as in 'try x + F()'
A try block covers every statement in it, so the calls inside need no try of their own.
The function must throw
With no handler around the call, the error leaves through the enclosing function's own throws channel, so that function must declare one:
error: call to 'ParseNumber' can throw 'DigitError', but 'Main' does not throw
help: handle the error with 'try ... catch', or declare 'throws DigitError' on 'Main'
The success types need not match — only the error is passed on. A function returning an optional has no channel for an error either: absence and failure are different things. A throwing Main lets the top level of a program pass errors on with try.
The error must fit
An error is never converted on its way out. An error of type E leaves a function that throws F only when:
E and F | Example |
|---|---|
| the same type | DigitError into DigitError |
E is a member of the sum F | DigitError into DigitError | RangeError |
E is a sum whose members are all in F | DigitError | RangeError into DigitError | IoError | RangeError |
func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError {
let value = try ParseNumber(text);
if value > 100 {
throw RangeError { value: value };
}
return value;
}
Any other pair is rejected:
error: call to 'ParseNumber' can throw 'DigitError', but 'ParseWidth' throws 'SettingError'
note: an error passes on only as itself, as a member of a sum, or as part of a larger sum; it is never converted
help: handle the error with 'try ... catch', or add 'DigitError' to the 'throws' clause of 'ParseWidth'
Mapping errors
Adding context to an error, or converting it to the function's own error type, is a catch arm that throws the mapped value. On success the arm never runs and the success continues unchanged. On failure e owns the complete error, the arm runs once, and its throw leaves the function:
func ParseWidth(text: char8[..]) -> int throws SettingError {
let width = try ParseNumber(text) catch { e => throw SettingError { name: "width", column: e.position + 1 } };
return width;
}
The arm is the place to add what the error does not carry — here, the name of the setting and a 1-based column — and it may use any local in scope.
- The arm's own
throwis not mapped again: an arm is outside its handler, so the error goes to the next handler out or to the caller. - The thrown value converts to the function's error type as any
throwdoes;throw 5there, in a function that throwsSettingError, is a type error. - An arm may leave another way — with
return, or a call toPanic— or produce a fallback value instead of throwing. - The arm reads and moves the surrounding locals under the ordinary rules, on a path that always leaves; a local moved only inside it is still owned on the continuing path.
An error sum whose members map differently is matched, inside the arm or in a helper function:
func ToConfig(error: ParseError | IoError, line: int32) -> ConfigError {
return match error {
parse: ParseError => ConfigError { kind: 1, detail: parse.position * 100 + line },
io: IoError => ConfigError { kind: 2, detail: io.code * 100 + line }
};
}
func Load(text: int32, line: int32) -> int32 throws ConfigError {
let value = try Read(text) catch { e => throw ToConfig(e, line) };
return value + 1;
}
The removed spelling value? else (e => mapped) is error: '? else' is not supported, with help: write 'try value catch { e => throw mapped }'.
From absence to an error
? on an optional passes on absence, never an error. When absence should be an error, the coalescing fallback says which one:
func PriceOf(code: int) -> int? {
return if code == 1 { .Some(250) } else { none };
}
func Total(code: int, count: int) -> int throws UnknownProduct {
let price = PriceOf(code) ?? throw UnknownProduct { code: code };
return price * count;
}
A function that returns U? throws F can pass on both: try passes an error on, and ? on an optional returns none.
? does not pass errors on
A postfix ? only propagates the absence of an optional. On a throwing call it is rejected:
error: '?' does not propagate errors
help: write 'try' before the expression to pass the error on
? does not apply to Core's Result either: a stored outcome is an ordinary variant, matched or asked about with is.
Ownership
A throw site moves its success onward and its error to the handler or the caller with their move operations, so an error or success whose move is prohibited, or one that is a reference, is rejected at the site — when a generic is instantiated, too. The state of each local at a throw site is the state a handler's arms start from.
See also
- Errors —
throws,throwand error types - Handling errors — deciding here instead of passing on
- Optional propagation —
?, which passes on absence - Learn: Propagate, Error mapping, Error sum, Absence to error, Fallible main
Handling
Handling the error of a throwing call where it happens: try ... catch with exhaustive arms, try blocks, try? and deliberate discards, and cleanup with defer instead of finally.
Panics
Stopping the program on a bug: Panic, Assert, DebugAssert, #NoReturn functions, the run-time checks that panic, and what a panic does not do.