In a Swift do-catch, which catch clause runs for a thrown error, and how do case, as, is and where patterns match?
answer
- source order, not specificity
- first matching clause wins
- where false means keep looking
- implicit error only in bare catch
basics
~20 sSwift tests catch clauses in source order and runs the first whose pattern matches: a case pattern can bind associated values, let x as T casts, is T tests the type, and where adds a condition. Unmatched errors propagate.
solid answer
~40 sWhen a `try` in the `do` block throws, Swift checks the `catch` clauses top to bottom and runs the **first** one whose pattern matches; it does not search for the most specific. `catch ParseError.wrongColumnCount(let line, let found)` matches one case and binds its values, `catch let e as ParseError` binds the whole value as that type, `catch is ReadError` only tests the type, and a `where` clause adds a condition, so a false condition moves on to the next clause. Several comma-separated patterns may share a clause if they bind the same names and types. Only a pattern-less `catch` binds the implicit `error`. If nothing matches, the error propagates, so in a nonthrowing function the chain must end with a clause that always matches, normally a bare `catch`.
code
swift · 29 linesenum ReadError: Error {
case fileNotFound(path: String)
case notUTF8(path: String)
}
enum ParseError: Error {
case wrongColumnCount(line: Int, found: Int)
case unterminatedQuote(line: Int)
}
func importContacts(from path: String) throws -> Int {
throw ParseError.wrongColumnCount(line: 12, found: 2)
}
func run(_ path: String) {
do {
let count = try importContacts(from: path)
print("imported \(count)")
} catch ReadError.fileNotFound(let path), ReadError.notUTF8(let path) {
print("cannot read \(path)")
} catch ParseError.wrongColumnCount(let line, let found) where found == 0 {
print("line \(line) is blank")
} catch let parse as ParseError {
print("parse problem: \(parse)")
} catch {
print("unexpected: \(error)")
}
}
run("contacts.csv")go deeper
Recall that catch clauses run top to bottom, the first match wins, and a bare catch at the end catches everything and names it error.
Explain each pattern form, what it binds, how where and multi-pattern clauses behave, and why a nonthrowing function needs a clause that always matches.
Show when to handle a stage error locally and when to let it propagate, and how clause order and a trailing catch keep new error cases from crashing or vanishing.
Weigh how much handling belongs at each layer: catching narrowly near the failure versus one general handler at the boundary that logs and maps errors for the user.
## How a catch clause is chosen A `do` statement can carry any number of `catch` clauses. When a `try` inside the `do` block throws, Swift does not look for the "best" clause; it follows a fixed procedure: 1. The remaining statements of the `do` block are skipped. 2. The thrown value is tested against each `catch` clause **in source order**. 3. The **first** clause whose pattern matches (and whose `where` condition, if any, is true) runs. 4. If no clause matches, the error **propagates** out of the whole `do` statement to the enclosing scope. Order is therefore part of the meaning. A general clause placed above a specific one hides it: writing `catch { }` before `catch is ParseError { }` makes the second unreachable, and Swift 6.4 warns "case will never be executed". ## The patterns a catch accepts A `catch` takes ordinary Swift patterns, the same family a `switch` case uses (the pattern rules themselves belong to the material on enum case patterns). The ones that matter for errors: | Clause | Matches | Binds | |---|---|---| | `catch ParseError.unterminatedQuote` | that enum case, any associated value | nothing | | `catch ParseError.wrongColumnCount(let line, let found)` | that case | the associated values | | `catch let parse as ParseError` | any `ParseError` value | `parse`, typed as `ParseError` | | `catch is ReadError` | any `ReadError` value | nothing | | `catch <pattern> where <condition>` | the pattern, only if the condition is true | the pattern's bindings | | `catch` | every error | the implicit constant `error` | Two details trip people up: - The implicit `error` constant exists **only** in a clause without a pattern. Inside `catch ParseError.wrongColumnCount(let line, let found)` the name `error` is not bound; Swift 6.4 even resolves the bare word to the `#error` macro and asks for a leading `#`. - A `where` clause that is false does not stop the search. The error moves on to the next clause, exactly like a `switch` case guard. ## Several patterns in one clause A clause may list patterns separated by commas, as in `catch ReadError.fileNotFound(let path), ReadError.notUTF8(let path)`. The clause matches if any pattern matches. Every pattern must bind the **same names with the same types**; binding `path` as a `String` in one pattern and as an `Int` in another fails with "pattern variable bound to type 'Int', expected type 'String'". ## Exhaustiveness and propagation With plain `throws`, the error inside a `do` block has the static type `any Error`. Swift considers a set of `catch` clauses exhaustive only when one of them **cannot fail to match**, which in practice means a final clause with no pattern or with the wildcard pattern `catch _`. Listing every case of `ParseError` is not enough, because the body could throw some other type. What happens to an unmatched error depends on the enclosing function: - In a **throwing** function, it propagates to the caller, which is often exactly what you want: handle the stage errors you can fix here and let the rest travel up. - In a **nonthrowing** function, the compiler rejects the code with "errors thrown from here are not handled because the enclosing catch is not exhaustive". The fix is a final pattern-less `catch` or marking the function `throws`. The book's own example makes the point: a clause that lists every current case of an error enum still lets future cases propagate, which is why a general `catch` usually closes the chain. ## Reading the example In the snippet, `importContacts` throws `ParseError.wrongColumnCount(line: 12, found: 2)`. The `ReadError` clause does not match. The next clause matches the case, binds `line` and `found`, but `found == 0` is false, so Swift moves on. `catch let parse as ParseError` matches and prints `parse problem: wrongColumnCount(line: 12, found: 2)`. The final `catch` would have handled anything else, such as an error type added later.
- What does Swift do with a catch clause placed after a pattern-less catch?It never runs, because the bare `catch` above it matches every error first. Swift 6.4 compiles the code but warns "case will never be executed" on the later clause. Order the chain from specific to general, and keep the bare `catch` last.
- Can one catch clause list two error patterns that both bind a value?Yes, separate them with commas, as in `catch ReadError.fileNotFound(let path), ReadError.notUTF8(let path)`. Each pattern must bind the same names with the same types; binding `path` as `String` in one and `Int` in the other fails with "pattern variable bound to type 'Int', expected type 'String'".
- Why can a nonthrowing function still fail to compile when its catch clauses list every case of ParseError?With plain `throws` the `do` body's error type is `any Error`, so Swift cannot know the body throws only `ParseError`, and case or type patterns can always miss. It reports "errors thrown from here are not handled because the enclosing catch is not exhaustive". Add a final bare `catch` or mark the function `throws`.
Catch clauses work like the pigeonholes in a mailroom checked from left to right: a letter goes into the first slot whose label fits, even if a better-labelled slot sits further along, and a letter that fits none is sent on to the next office.
- Swift runs the most specific catch clause, wherever it appears in the chain.
- Listing every case of my error enum makes an untyped do-catch exhaustive.
- The implicit error constant is available inside every catch clause.
- When a where condition is false, the error leaves the do-catch at once.
- An error no clause matches is silently dropped at the end of the do-catch.