In Swift, how do you define an error type, mark a function as throwing, and handle its errors with do-catch?
answer
- a protocol with no requirements
- keyword before the return arrow
- a marker on every throwing call
- pattern-less catch binds a constant
basics
~20 sConform a type, usually an enum, to Error, write throws before the return arrow, and mark each throwing call with try. Inside do, an error jumps to the first matching catch; a pattern-less catch binds it as error.
solid answer
~40 sAn error is any value whose type conforms to `Error`; an enum with associated values is the usual choice, such as `ParseError.wrongColumnCount(line:expected:found:)`. A function that can fail is declared `throws` before its `->`, and it fails with `throw`. Every call to it needs `try`; without a surrounding `do`-`catch` the error propagates to the caller, which must itself be `throws`. Inside `do { }`, a thrown error transfers control to the first `catch` whose pattern matches, and a bare `catch` matches everything and binds the implicit constant `error`. A nonthrowing function must handle every error, and the compiler checks that statically. A `throw` does not unwind the stack like an exception; it costs about as much as a `return`.
code
swift · 26 linesenum ParseError: Error {
case wrongColumnCount(line: Int, expected: Int, found: Int)
}
func parseRow(_ text: String, line: Int) throws -> [String] {
let fields = text.split(separator: ",", omittingEmptySubsequences: false).map(String.init)
guard fields.count == 3 else {
throw ParseError.wrongColumnCount(line: line, expected: 3, found: fields.count)
}
return fields
}
func parseAll(_ rows: [String]) throws -> [[String]] {
var result: [[String]] = []
for (index, row) in rows.enumerated() {
result.append(try parseRow(row, line: index + 1)) // an error propagates out
}
return result
}
do {
let rows = try parseAll(["7,Ada,[email protected]", "8,Bob"])
print("parsed \(rows.count) rows")
} catch {
print("import failed: \(error)")
}go deeper
Recall the three keywords and where they go: Error conformance on the type, throws before the arrow, try on every throwing call, and the implicit error constant in a bare catch.
Explain propagation precisely: which caller must be throws, how catch clauses are tried in order, and the diagnostics the compiler gives when a path leaves an error unhandled.
Show how you model failures per stage, for example one enum per import stage with associated values that let a caller recover or report, and why a class error is checked for Sendable.
Discuss error types as part of a module's interface: which details a caller can act on, how stage-specific enums keep layers separate, and why throwing is cheap enough for ordinary control paths.
## Representing an error In Swift an **error** is any value whose type conforms to the `Error` protocol from the standard library. The protocol has no requirements you must implement (its underscored members get default implementations), so the conformance mainly says "this type may be thrown". In Swift 6.4 `Error` refines `Sendable`, which matters for the class case below. The book and the standard library's own documentation describe an **enumeration** as well suited to a group of related failures, with **associated values** carrying the details a caller needs to recover or report: - `case wrongColumnCount(line: Int, expected: Int, found: Int)` tells the caller exactly which row of a CSV file broke and how. - A **structure** fits when every failure shares the same data, such as a line and column plus a `kind` field. - A **class** works, but it is checked against `Sendable`: a non-final class with a `var` property draws the warnings "non-final class ... cannot conform to the 'Sendable' protocol" and "stored property ... is mutable" in Swift 6 language mode. A CSV importer typically has one enum per stage, for example `ReadError` for opening the file, `ParseError` for splitting rows and `ValidationError` for checking fields, so that a `catch` can tell the stages apart. ## Throwing and propagating A function, method or initializer that can fail writes **`throws`** after its parameter list and before the return arrow: `func parseRow(_ text: String, line: Int) throws -> [String]`. Inside it, `throw ParseError.wrongColumnCount(...)` ends the function at once; no value is returned. Every call to a throwing function must be marked with **`try`** (or `try?` / `try!`). The marker exists so that a reader can see each point where control may leave the current flow. One `try` covers the whole expression to its right, so `try count(a) + count(b)` marks both calls, while `1 + try count(c)` is rejected with "'try' cannot appear to the right of a non-assignment operator". When a throwing function calls another throwing function with plain `try` and does not catch, the error **propagates**: it leaves the caller as well and travels to the next frame up. That is how `parseAll` above passes a row's failure to its own caller without a line of handling code. ## Handling with do-catch A `do` statement runs its block; if any `try` inside it throws, control jumps to the `catch` clauses: 1. Swift tests the clauses top to bottom against the thrown value. 2. The first clause whose pattern matches runs, and the rest are skipped. 3. A `catch` with **no pattern** matches every error and binds it to an implicit local constant named `error`. 4. If no clause matches, the error propagates out of the `do` statement to the surrounding scope. The book lists four ways to deal with an error: propagate it, handle it with `do`-`catch`, turn it into an optional with `try?`, or assert it cannot happen with `try!`. ## What the compiler enforces Swift checks error handling statically, so most mistakes are compile errors rather than crashes: | Mistake | Swift 6.4 diagnostic | |---|---| | Calling a throwing function with no `try` | `call can throw, but it is not marked with 'try' and the error is not handled` | | `try` in a nonthrowing function with no `do`-`catch` | `errors thrown from here are not handled` | | A `do`-`catch` in a nonthrowing function whose clauses can miss an error | `errors thrown from here are not handled because the enclosing catch is not exhaustive` | | `try` before a call that cannot throw | warning: `no calls to throwing functions occur within 'try' expression` | A nonthrowing function must therefore handle every error itself. Top-level code in a script or `main.swift` may let an error escape, and then the program stops with "Fatal error: Error raised at top level". You also cannot overload two functions that differ only in whether they throw; the second one is an "invalid redeclaration". Overloading on whether a **parameter** of function type throws is allowed. ## Cost and mental model Swift's error handling looks like exceptions, but the book is explicit that it does **not unwind the call stack**, and a `throw` performs comparably to a `return`. A throwing function effectively has a second way to return. With plain `throws` the error travels as `any Error`, which the compiler documentation says involves a heap allocation and reference counting; typed throws, covered in the material on `throws(E)`, can avoid that box.
- Does a Swift throw unwind the call stack the way an exception does, and what does it cost?No. The Swift book says error handling does not unwind the call stack and that a `throw` performs comparably to a `return`: the error comes back through the normal return path to the nearest handler. The one cost to know is that a plain `throws` carries the error as `any Error`, a box that can mean a heap allocation and reference counting; typed throws avoids that box.
- What happens when an error is thrown from top-level code and nothing catches it?Top-level code in a script or `main.swift` may leave an error unhandled, and then the program stops at run time with "Fatal error: Error raised at top level" plus the error. Inside a nonthrowing function the same situation is a compile error, so it never reaches run time there.
- Can you declare both `func load() -> Int` and `func load() throws -> Int` in Swift?No. Throwing is part of the function type but not enough to overload on, so the second declaration is an invalid redeclaration of `load()`. You can overload on whether a function-typed parameter throws, for example `f(callback: () -> Int)` beside `f(callback: () throws -> Int)`.
- Swift errors must be classes that inherit from a base Error class.
- Writing try handles the error, so no do-catch or throws is needed.
- A call inside a do block needs no try because do marks it.
- A nonthrowing function can let an error escape to its caller.
- A Swift throw unwinds the stack and is far slower than a return.