DocsLanguage Guide
Error Handling
Typed throws, try and its forms, do-catch, rethrows, throwing iteration and panics.
Error handling is how a program responds to things going wrong that it can expect and recover from: a file that isn't there, a number that doesn't parse, a server that doesn't answer. Sable's errors are typed and checked: a function says in its signature what it may throw, every call that may throw is marked with try, and the compiler makes sure every error ends up somewhere.
They look like Swift's, but are typed by default, as Swift's throws(E) is, and are compiled to an ordinary return value rather than to stack unwinding, so throwing costs about as much as returning. Bugs — states the program should never reach — are a different thing, handled by panics, which this chapter covers at the end.
Representing errors#
An error is a value of any type, but it's usually a union whose cases name what went wrong and carry the details (unions are covered in Enums and Unions):
union IoError: Error { NotFound(path: String) Denied Interrupted}union ParseError: Error { Empty BadDigit(at: Int) Overflow}A union says exactly which failures are possible, so a caller can handle each one, and the compiler can check that it did. The : Error conformance is explained next.
The Error protocol#
The standard library's Error protocol is what error types conform to. It requires nothing you must write — both its requirements have defaults — and gives every error two things:
description(), a sentence for a person to read. By default it's the value written out, asDebugwrites it.source, the error underneath this one, if another error caused it. By default it'snone.
Error refines Debug and Sendable, so an error can be printed for debugging and passed between tasks. Conform by saying so, and override what you want to improve:
union ConfigError: Error { Missing(key: String) Unreadable(cause: IoError) fn description() -> String { return match self { case .Missing(let key) => "the setting '\(key)' is missing" case .Unreadable(_) => "the configuration file could not be read" } } var source: (any Error)? { get => match self { case .Unreadable(let cause) => cause default => none } }}Walking source from error to error gives the chain of causes, as Rust's Error::source does. Any type may still be thrown, even one that doesn't conform to Error (a String, say); such a value is described by what it is.
Throwing functions#
A function that can fail says what it throws with throws(E) after its parameters:
fn readFile(_ path: String) throws(IoError) -> String { if path.isEmpty { throw IoError.NotFound(path: path) } return "contents of \(path)"}throw leaves the function at once with the error, just as return leaves it with a value. Where the error type is known, a leading dot is enough: throw .Denied.
A function may throw only what it declares. A throw in a function that declares no throws, or of a type it doesn't declare, is an error (S3033, S3054). To throw errors of several types, declare their structural union, throws(IoError | ParseError).
Bare throws with no type means throws(any Error): the function may throw an error of any type, boxed as an existential. That suits a high-level function whose callers will only report the error, not handle each case. Through an any Error you can still call description(), read source, and print it.
fn loadEverything() throws -> Int { let text = try readFile("a.txt") // IoError, erased to any Error return text.count}Initialisers throw in the same way, init(_ text: String) throws(ParseError) (Initialization), and so do closures: a closure throws what its body throws, unless it says throws(E) itself. What a function throws is part of its type: (String) throws(IoError) -> String.
Calling a throwing function: try#
Every call that may throw is marked with try. The mark makes the places where control may leave visible when you read the code:
fn wordCount(_ path: String) throws(IoError) -> Int { let text = try readFile(path) return text.split(separator: " ").count}If readFile throws, try passes the error on: wordCount stops and throws it to its own caller. This propagation is why wordCount must declare throws(IoError) too. The compiler checks all of it:
- a throwing call without
tryis an error (S3032); - a
trywhose error has nowhere to go, because the function doesn't throw that type and nothing catches it, is an error (S3033); - a
tryover an expression that can't throw anything is an error too (S3036), so marks don't pile up where they mean nothing.
One try covers the whole expression after it, so try readFile(a) + readFile(b) needs only one.
Converting errors with From#
Often a function calls something that throws a lower-level error and wants to throw its own type. A conformance to From says how to make one error from another:
union StoreError: Error { Unavailable(shard: U64)}union ServiceError: Error { NotFound(id: U64) Upstream(cause: StoreError)}extension ServiceError: From<StoreError> { static fn from(_ e: StoreError) -> ServiceError => .Upstream(cause: e)}fn loadUser(_ id: U64) throws(ServiceError) -> String { return try loadRecord(id) // loadRecord throws StoreError}fn loadRecord(_ id: U64) throws(StoreError) -> String { if id % 4 == 0 { throw .Unavailable(shard: 0) } return "user \(id)"}With the conformance in place, the try in loadUser converts any StoreError to a ServiceError on its way out. Without it, the try is an error (S3054), whose message suggests the conformance, widening the declaration, or catching the error.
This is the only implicit conversion in the language. It's worth the exception: writing the conversion by hand at every call site is exactly the boilerplate that typed errors would otherwise cost.
Handling errors with do-catch#
do runs a block, and the catch clauses after it handle what it throws. Each catch may give a pattern — any pattern from Pattern Matching — and the first clause whose pattern matches the error runs:
fn show(_ path: String) { do { let text = try readFile(path) print(text) } catch .NotFound(let p) { print("no file at \(p)") } catch .Denied { print("not allowed to read \(path)") } catch { print("could not read: \(error)") }}A catch with no pattern catches everything that's left. Inside it the error is bound, implicitly, as error, with the type the block throws. A catch may also add a where condition, with or without a pattern:
fn createLockFile() throws(IoError) { }var tries = 0while true { do { try createLockFile() break } catch IoError.Interrupted where tries < 3 { tries += 1 // interrupted: go round again } catch { print("giving up: \(error)") break }}Because errors are typed, the catches can be exhaustive without a catch-all. If the patterns together cover every case of what the block throws, the do throws nothing:
fn status(_ path: String) -> String { do { return try readFile(path) } catch .NotFound(_) { return "missing" } catch .Denied { return "forbidden" } catch .Interrupted { return "try again" }}What the catches don't cover is passed on. In a function that throws that type, it propagates as a try would; in one that doesn't, the uncovered cases are an error (S3033), and the message names the case still missing, '.Denied', say. A catch with a where condition never counts as covering anything, since its condition may be false.
When a do block throws several types, the error in its catch-all has their union type. A try inside a catch clause isn't covered by that same do: it needs a do or a throwing function around it.
Converting errors to optionals: try?#
try? e gives e's value as an optional, or none if it throws. The error itself is dropped:
fn parsePort(_ text: String) throws(ParseError) -> Int { guard let n = text.toInt() else { throw .BadDigit(at: 0) } return n}let port = try? parsePort("80a") // Int?, none herelet value = try? parsePort(text) ?? 8080Use it when you only care whether something worked. The result is always optional, so try? f() where an Int is wanted is an error (S3004).
Inline fallbacks: try … catch#
try e catch { … } supplies a value to use in place of e when it throws. The braces hold a block whose last line is the fallback, and the error is bound as error inside it:
fn settingsText() -> String { return try readFile("settings.toml") catch { "" }}fn describe(_ path: String) -> String { return try readFile(path) catch { "unreadable: \(error)" }}The fallback may also be an expression written straight after catch. Either way the result has the plain type, not an optional, and error is only in scope inside the fallback.
Asserting no error: try!#
try! e gives e's value, and traps if it throws. It's for calls you know can't fail with the arguments given — a literal that is known to parse, for example:
let spec = try! FormatSpec.parse(".2")As with ! on an optional, a try! that fails stops the program. Use it only where an error would mean a bug.
throw as an expression#
throw may also be written where a value is expected. It never produces one — it leaves — so its type is Never, which fits any type. It takes the whole expression after it, just as the statement does.
That makes a missing value easy to turn into an error:
fn port(from settings: [String: Int]) throws(ConfigError) -> Int { return settings["port"] ?? throw ConfigError.Missing(key: "port")}and lets an arm of a match expression fail:
union Fit { One(Int) Gap(Int, Int) Overlap(Int, Int)}union TimeZoneError: Error { Skipped, Ambiguous }fn offset(_ fit: Fit) throws(TimeZoneError) -> Int { return match fit { case .One(let v) => v case .Gap(_, _) => throw TimeZoneError.Skipped case _ => throw .Ambiguous }}The throwing arms give no type, so the match's type comes from the others. The same goes for arms that return, break or continue.
Rethrowing functions#
A function that takes a closure often throws only if the closure does. rethrows says that: the function throws exactly when its closure argument throws, and what it throws:
fn measured<T>(_ label: String, _ body: () throws(IoError) -> T) rethrows -> T { print("starting \(label)") defer { print("finished \(label)") } return try body()}let n = measured("sum") { 40 + 2 } // no try: this closure can't throwlet text = try measured("read") { try readFile("a") } // this one canAt each call, a closure that can't throw makes the call non-throwing, so it needs no try (and one would be S3036); a throwing closure makes the call throw, so it needs try (S3032). A rethrows function must have a throwing closure parameter (S3048), and may throw only what its closures throw: throwing an error of its own, or calling another throwing function, is S3049. A closure can't be declared rethrows itself, as its type already says what it throws.
rethrows(E) throws E as well as what the closures throw. The sequence algorithms are rethrows(Failure): map, filter and the rest throw what their closures throw and what going through the sequence throws (next section). Over an array, with closures that can't throw, neither applies, so they need no try.
Throwing iteration#
Some sequences can fail as they're gone through — the lines of a file being read, the records of a parse. The Iterator and Sequence protocols (and their async forms) have an associated type Failure for this: what getting the next element may throw. It's Never unless the iterator's next() says otherwise:
mutating fn next() throws(Failure) -> Element?A loop over a sequence whose Failure isn't Never is written for try (or for try await for an async one). If getting an element throws, the loop leaves with the error, as a try would:
struct Record { var text: String }fn parseRecord(_ line: String) throws(IoError) -> Record { if line.isEmpty { throw .Interrupted } return Record { text: line }}fn records(_ path: String) throws(IoError) -> some Sequence<Record> { for line in try readFile(path).split(separator: "\n") { yield try parseRecord(line) }}for try record in records("orders.csv") { print(record.text)}Forgetting the try is an error (S3032), as on a call. Arrays, ranges, collections and generators that can't fail have a Failure of Never, cost nothing extra, and loop with a plain for. A Collection can never fail.
Generic code either lets the failure out or refuses sequences that can fail:
fn total<S: Sequence>(_ s: S) throws(S.Failure) -> Int where S.Element == Int { var sum = 0 for try x in s { sum += x } return sum}fn quietTotal<S: Sequence>(_ s: S) -> Int where S.Element == Int, S.Failure == Never { var sum = 0 for x in s { sum += x } return sum}In an opaque result type, some Sequence<T> says the sequence can't fail — a defaulted associated type left out of the angle brackets is its default, and Failure's is Never — while some Sequence<T, E> says it may throw E. In a generator's result, as in records above, a Failure left out is whatever the generator body throws. Generators are covered in Functions; protocols' associated types in Protocols.
Cleaning up with defer#
defer blocks run when their scope exits, however it exits — including when an error is thrown out of it. That makes them the place for cleanup that must always happen:
fn process(_ path: String) throws(IoError) -> Int { print("opening \(path)") defer { print("closing \(path)") } let text = try readFile(path) // if this throws, "closing" still prints return text.count}A defer block itself can't throw: a try inside one has nowhere to go (S3033). Control Flow covers defer and using.
How errors are compiled#
A Sable throw is a return. A function declared throws(E) returns its value in the usual registers and its error in a dedicated register (Swift's convention: x21 on arm64, r12 on x86-64), and the caller checks a flag after the call — a branch that's predicted not taken. There are no unwinding tables, no landing pads and no hidden costs on the path that doesn't throw.
That's why typed errors are cheap enough to use everywhere, including in hot code, and why Sable doesn't need a separate Result-returning style for performance. (The library does have Outcome<T, E>, a union of .Ok and .Err, for when you want to store a success or failure as a value.)
An error that leaves main uncaught is reported as fatal error: uncaught error: and its description, with the place it was thrown from, and the program ends with status 1.
Panics#
Errors are for failures a caller can handle. A panic is for a state that means the program itself is wrong — a broken invariant, an index out of range, code that was never meant to run. A panic stops the program: it prints fatal error: , the message and the caller's place, and aborts. It does not unwind, and normal code can't catch it.
The standard library's panicking functions are:
| Function | Stops the program |
|---|---|
precondition(cond, message) |
if cond is false, in every build |
preconditionFailure(message) |
always, in every build |
assert(cond, message) |
if cond is false, in debug builds only |
assertionFailure(message) |
always, in debug builds only |
fatalError(message) |
always |
todo(message) |
always: the code isn't written yet |
unimplemented(message) |
always: the operation isn't supported, and won't be |
unreachable(message) |
always: this code should never run |
The ones that always stop return Never, so they can end a function that must return a value, or fill an arm of a match expression:
fn colour(_ name: String) -> Int { if name == "red" { return 0xFF0000 } fatalError("no colour called \(name)")}fn sign(_ n: Int) -> String { if n < 0 { return "-" } if n > 0 { return "+" } if n == 0 { return "0" } unreachable("every Int is negative, positive or zero")}assert checks only where DEBUG is defined — an unoptimised build, or a profile with debug-assertions turned on — in library code as in yours. Use precondition for checks that must hold in release builds too. (In a file that imports Sable.Testing, bare assert is that module's, a test assertion checked in every build.) The messages are evaluated only if the check fails, so building one costs nothing otherwise.
A trap also happens when you force-unwrap a none, on arithmetic overflow, and on an out-of-range index. Set SABLE_BACKTRACE to get a backtrace with each report, and see Documentation and Testing for testing code that is supposed to panic.
Reporting the caller's place#
Each panicking function reports the line that called it, not a line inside the library. It does this with default parameter values that the compiler fills in at the call site:
fn require(_ ok: Bool, _ message: String, file: String = #file, line: Int = #line) { if !ok { fatalError("\(message) at \(file):\(line)") }}let items = ["a", "b"]require(items.count > 0, "no items") // reports this lineA parameter whose default is #file, #line, #column or #function takes the place of the call, not of the declaration. You can use them in your own functions for the same purpose.
#expression goes further: a parameter with that default receives what the call's first argument was written as, together with the value each part of it had as it was evaluated. That's how a test's expect(a.count == 2) can say what a.count actually was when it failed. Its type must be a class with static fn begin() and fn note<T>(_ text: String, _ value: T) -> T, such as Sable.Testing's CapturedExpression.
These directives are only meaningful as a default, alone, and #expression not on the first parameter, since it describes that argument; anything else is an error (S3517).