Handling Errors
A function that calls a throwing function either handles the error itself or passes it on. This page covers handling it: try ... catch on one expression, a try block over several statements, and try?, which drops the error. Passing it on is Passing errors on.
try-catch-expr = "try" expr "catch" "{" match-arm { "," match-arm } [ "," ] "}"
try-optional = "try?" expr
try-block = "try" block "catch" "{" match-arm { "," match-arm } [ "," ] "}"
| Form | The error goes | The result |
|---|---|---|
try expr catch { arms } | to the arms | the success, or what the arm produced |
try { ... } catch { arms } | from any statement in the block, to the arms | none — it is a statement |
try? expr | nowhere: it is dropped | the success made present, T?, or none |
try ... catch
catch hands the error of the expression after try to arms that match it. A success passes through unchanged and no arm runs; the value of the whole expression is the success:
variant DigitError {
Blank,
Letter(char)
}
func Lenient(c: char) -> int {
return try ReadDigit(c) catch {
.Blank => 0,
.Letter('O') => 0,
.Letter(_) => -1
};
}
- The arms are exactly the arms of
match error { ... }: patterns, the_default,|alternatives, guards, typed patterns over an error sum, block arms, and a trailing comma. See Match. - The arms must cover every error, and the diagnostic names what is missing as a match's does: leaving out
.Blankabove iserror: match on 'DigitError' is not exhaustive; missing DigitError::Blank. The usual fix is a_arm, or an arm that binds the whole error,e => .... - Each arm either produces a value that converts to the operand's type or leaves through
throw,return,break,continue, a call toPanicor a#NoReturnfunction. A leaving arm never decides the result type. - The type the context expects of the whole expression is the operand's and every arm's, so
let kept: Result<int, DigitError> = try .Success(ReadDigit(c)) catch { e => .Failure(e) };builds both cases without naming the variant.
When several calls throw different errors, the handler takes the sum of them, and typed patterns tell them apart:
func LoadWithDefaults() -> Options | Defaults throws IoError {
return try Read() catch {
_: ParseError => Defaults {},
e: IoError => throw e
};
}
Passing an error on from an arm
Nothing is rethrown implicitly: an error that the arms do not want is passed on by an arm of its own, e => throw e. An arm is outside its handler, so its throw — and a call it marks with try — goes to the next handler out, or out of the function through its throws channel, and the same catch never sees it again:
func Strict(c: char) -> int throws IoError {
let digit = try ReadDigit(c) catch { _ => throw IoError { code: 22 } };
return digit * 2;
}
let trusted = try ReadDigit('8') catch { _ => Panic("a literal digit always reads") };
Converting the error on the way out — adding context, or mapping it to the function's own error type — is the same kind of arm; see Mapping errors.
A fallback for every error
_ => fallback is the counterpart of ?? for a throwing call: the success, or fallback for any error.
let digit = try ReadDigit(c) catch { _ => 0 };
There is no brace-less form; the braces are always written.
Block arms
An arm whose body is a block { … } yields the expression it ends with, written without a ;. A block that ends otherwise completes with (), which is valid only where the operand returns nothing — unless the block ends by leaving:
try Close(false) catch {
e => {
PrintLine("close failed with {}", e.code);
}
};
let digit = try ReadDigit(c) catch {
e => {
PrintLine("not a digit");
0
}
};
Where the operand has a value, an arm that completes with () is rejected rather than inventing one:
error: a block arm completes with '()', but 'catch' must produce a value of type 'int32'
help: end the block with the value written without a ';', or leave it with 'throw', 'return', or a call to 'Panic'
Precedence
try has the lowest precedence of any operator: it covers the whole expression to its right, and catch handles every throw site in it.
let total = try ReadDigit('x') + 1 catch { _ => 10 }; // 10: the whole sum is replaced
let scaled = (try ReadDigit('4') catch { _ => 0 }) * 10; // 40
Evaluation stops at the first throw site that fails, so nothing to its right runs. A try is written where an expression starts, never to the right of another operator; see Passing errors on.
try blocks
A try block covers every statement in it, those in nested blocks included, and hands the error of any of them — including a throw written in it — to its catch arms. It is a statement, and its arms run for their effect, as the arms of a match statement do:
func Configure(path: char8[..]) {
try {
let options = Parse(ReadText(path));
Apply(move options);
} catch {
_: IoError => PrintLine("cannot read {}", path),
_: ParseError => PrintLine("{} is not a configuration", path)
}
}
- The calls inside need no
tryof their own; the block covers them. - The arms take the sum of every error the block's throw sites and
throwstatements raise, and must cover it. - A deferred statement inside the block is not covered, because it runs as the scope is left, and neither are the arms of a handler nested in the block.
break,continueandreturnleave atryblock as they leave any block.- When an error leaves the block, its defers run and its locals are destroyed, in the order a return runs them, before the arm runs.
A try block always has arms:
error: a 'try' block needs 'catch' arms
The help offers adding catch { e => ... } after the block, or writing try before a call to pass its error on.
try?
try? handles every error of its operand by dropping it: the error is destroyed where it is dropped, and the result is the operand's value made present, or none.
let digit: int? = try? ReadDigit(c);
let value = (try? ReadDigit(c)) ?? 0;
| Operand returns | try? gives |
|---|---|
T | T? |
T? | T?? — absence and an error stay distinct |
| nothing | ()? |
try? takes no arms (error: 'try?' takes no 'catch' arms). Because try covers everything to its right, ?? included, a fallback needs the parentheses: (try? F()) ?? fallback.
Ignoring an error
An unmarked throwing call is an error, so an error is never dropped by accident. Ignoring one is always written out:
| Write | For |
|---|---|
try? F(); | any call: the result is an optional nobody reads |
try F() catch { _ => {} }; | a call that returns nothing |
try F() catch { _ => fallback } | a call with a value, when the error has a stand-in |
try Close(file) catch { _ => {} };
A try that covers no throw site is a warning, warning: 'try' has no call that can throw.
Io::PrintLine returns IoError? — an optional that reports a console write problem. An optional may be ignored, which is why PrintLine(…); is a valid statement with no try.Cleanup and finally
There is no finally, and the word is reserved:
error: 'finally' is not supported
help: use 'defer' inside the try block
Code after a try { } catch { } whose arms do not leave always runs; cleanup that must run on every exit is a defer or a destructor, which run when an error leaves their scope as they do on a return.
A deferred statement and a destructor run while their scope or value is already being left, so no error may leave either. A call in them that can throw is written try? or try ... catch; a bare try there is error: an error cannot leave a deferred statement (or a destructor), with help: handle it with 'catch' or discard it with 'try?'.
Ownership
- The state of each local at a throw site is the state the arms start from, so a value moved after one throwing call and before another is possibly moved in the arms.
- An arm reads and moves the surrounding locals under the ordinary rules. A local moved only inside an arm that leaves is still owned on the path that continues after the handler.
- An arm that binds the error owns it and destroys it at its end, unless it moves it on; an error no arm binds is destroyed when its arm is chosen. An error whose move is prohibited cannot be bound by value.
Keeping the outcome
When the outcome itself has to be stored — in a field, a container, or for later — build Core's ordinary Result<T, E> from the call:
let kept: Result<int, DigitError> = try .Success(ReadDigit(c)) catch { e => .Failure(e) };
A stored Result is asked about with is, as in if kept is .Success(_), and taken apart with match. See Keeping an outcome.
Idioms
| Wanted | Write |
|---|---|
| a fallback value for any error | try F() catch { _ => fallback } |
| a fallback per kind of error | try F() catch { .A => …, .B => … } |
| an expected success, where failure is a bug | try F() catch { _ => Panic("why it cannot fail") } |
| translate the error and keep failing | try F() catch { e => throw Wrap(e, context) } — see Mapping errors |
| pass the error on unchanged | try F() |
| ignore the error of a call that returns nothing | try F() catch { _ => {} }; |
| drop the error, keep an optional | try? F() |
| store the outcome | try .Success(F()) catch { e => .Failure(e) } into a Result<T, E> |
| cleanup on every exit | defer inside the try block |
See also
- Errors —
throws,throwand error types - Passing errors on — marking throw sites, and mapping errors
- Match and Patterns — the arm grammar
catchshares - Defer — cleanup that runs when an error leaves
- Learn: Outcome, Discard, Catch, Catch fallback
Overview
Typed throws: a function declares the error it can throw with throws E, sends one with throw, and every call that can throw is marked with try.
Propagation
Marking every throw site with try, passing an error on through the function's throws channel, mapping it with try ... catch { e => throw Map(e) }, and turning absence into an error with ?? throw.