skip to content

In Swift 6, what does declaring throws(ParseError) give a caller, and when does a typed throws signature cause trouble?

level: seniorimportance: should knowfreq 35%

answer

  1. SE-0413, Swift 6.0
  2. inferred error type in catch
  3. switch on error, no fallback
  4. closures and throw fall back

basics

~20 s

Since Swift 6.0, throws(ParseError) lets a do-catch infer error as ParseError, so a bare catch can switch over every case with no any Error box. It hurts when new error sources appear, enums grow, or closures lose the type.

solid answer

~40 s

Typed throws (SE-0413, Swift 6.0) restricts a function to one error type; plain `throws` is `throws(any Error)` and nonthrowing is `throws(Never)`. A caller whose `do` block only calls `throws(ParseError)` functions gets `error` typed as `ParseError` in a pattern-less `catch`, so a `switch` there is checked for exhaustiveness and needs no fallback. Exhaustiveness still needs a clause that always matches, normally that bare `catch`: separate `catch .caseA` and `catch .caseB` clauses are not enough. The type is lost when the block also contains a `throw` statement or a second error type, or when an unannotated closure calls the function. It causes trouble in public APIs, where adding a case breaks clients and a new dependency's errors must be wrapped, and the book notes that most Swift code does not specify an error type.

code

swift · 25 lines
swift
enum ParseError: Error {
    case wrongColumnCount(line: Int, found: Int)
    case unterminatedQuote(line: Int)
}

func parseRow(_ text: String, line: Int) throws(ParseError) -> [String] {
    if text.filter({ $0 == "\"" }).count % 2 != 0 { throw .unterminatedQuote(line: line) }
    let fields = text.split(separator: ",", omittingEmptySubsequences: false).map(String.init)
    guard fields.count == 3 else { throw .wrongColumnCount(line: line, found: fields.count) }
    return fields
}

func report(_ text: String) {          // nonthrowing: the do-catch below is exhaustive
    do {
        _ = try parseRow(text, line: 1)
    } catch {                          // error has type ParseError, not any Error
        switch error {
        case .wrongColumnCount(let line, let found): print("line \(line): \(found) columns")
        case .unterminatedQuote(let line): print("line \(line): open quote")
        }
    }
}

report("7,\"Ada")   // line 1: open quote
report("7,Ada")     // line 1: 2 columns

go deeper

for a junior

Recall the syntax throws(ErrorType), that it arrived in Swift 6.0, and that plain throws means any Error.

for a middle

Explain how a do block infers its error type, why a bare catch with a switch is exhaustive, and what throws(Never) means.

for a senior

Show where the type silently degrades to any Error, how you convert between stage error types, and why an internal parser is a better fit than a public API.

for a principal

Weigh exhaustive handling and no allocation against the API rigidity a concrete error type creates for modules others depend on.

## What typed throws declares Swift 6.0 introduced **typed throws** (SE-0413). Writing `throws(ParseError)` after a function's parameters says that the function can throw values of `ParseError` and nothing else. The compiler checks the body: throwing another type, or calling `try readFile()` where `readFile` is `throws(ReadError)` without handling it, fails with "thrown expression type 'ReadError' cannot be converted to error type 'ParseError'". Inside the function the type is known, so `throw .unterminatedQuote(line: line)` can use the short case syntax. Typed throws generalises the old forms: - plain `throws` is exactly `throws(any Error)`; - a nonthrowing function is equivalent to `throws(Never)`, and calls to a `throws(Never)` function need no `try`. The feature is part of the language, not of a mode: Swift 6.4 accepts it in Swift 5 language mode as well as Swift 6 mode. ## What the caller gains 1. **A typed `error` in `catch`.** When every `try` in a `do` block calls functions that throw the same concrete type, Swift infers that the `do` throws that type, and the implicit `error` in a pattern-less `catch` is a `ParseError`, not an `any Error`. 2. **Compile-time exhaustiveness.** A `switch error` inside that `catch` must cover every case. Add `case headerMissing` to `ParseError` later and every such switch in the module stops compiling until it handles the new case, which the book suggests for a library that catches all of its own errors. 3. **No existential box.** Untyped errors travel as `any Error`, which the compiler documentation says means a heap allocation and reference counting. A concrete error type avoids that, which is why the book names embedded systems without dynamic allocation as a use case. 4. **Precise generic pass-through.** `func each<E: Error>(_ body: (Row) throws(E) -> Void) throws(E)` gives callers the closure's own error type, and `E == Never` for a nonthrowing closure. ## Where exhaustiveness does not come from Catch exhaustiveness still depends on a clause that always matches. A nonthrowing function whose `do` calls a `throws(ParseError)` function and has only `catch .wrongColumnCount { }` and `catch .unterminatedQuote { }` fails with "errors thrown from here are not handled because the enclosing catch is not exhaustive", even though both cases are listed. The idiom is a single pattern-less `catch` containing a `switch`, as in the first example. ## Where the type is lost Inference is deliberately narrow, and several everyday shapes fall back to `any Error`: - **A `throw` statement inside the `do`.** For source compatibility a `throw` counts as throwing `any Error` during inference, so adding `throw ParseError.badQuote` to the block turns `error` back into `any Error`. Writing `do throws(ParseError) { ... }` states the type explicitly. - **Two error types.** `try readFile()` (`ReadError`) and `try parseRow(...)` (`ParseError`) in one block make the `do` throw `any Error`; Swift does not form a union. - **Unannotated closures.** Swift 6.4 infers a closure that calls a typed function as plain `throws`: `let f = { try parseRow("") }` has type `() throws -> Array<String>`, and `try lines.map { try parseRow($0) }` throws `any Error`. Annotate the closure, `{ (line) throws(ParseError) in ... }`, as in the second example. Full closure inference was left for the future (`FullTypedThrows` is still an experimental feature). ## When it hurts The book is direct: most Swift code does not specify an error type. Typed throws fits three cases: code that must avoid allocation, errors that are an implementation detail handled inside one module, and generic code that only passes a parameter's error through. Outside those, it costs: | Situation | Problem with a concrete type | |---|---| | A function gains a new dependency that throws a different type | it must catch and wrap that error, or change its signature | | A public enum gains a case | clients that switch over it exhaustively stop compiling when they rebuild from source | | A pipeline mixes stages | each boundary needs explicit conversion between error types | | Callers only log and show the error | the precision buys nothing | For a CSV importer, `throws(ParseError)` on an internal row parser that the import stage fully handles is a good fit; making the public `importContacts(from:)` typed would lock every future failure source into one enum.

  • Why does adding throw ParseError.badQuote to a do block stop the catch from seeing a ParseError?
    For source compatibility, Swift treats every `throw` statement as throwing `any Error` when it infers a `do` block's error type, so the block now throws `any Error` and the `switch` fails with "type 'any Error' has no member ...". Write `do throws(ParseError) { ... }` to state the type, and the `throw` can then use `.badQuote` directly.
  • What does throws(Never) mean, and where does it matter in practice?
    A `throws(Never)` function cannot throw, because no value of `Never` exists, so calls to it need no `try`. It matters in generic code: a `throws(E)` function called with a nonthrowing closure infers `E == Never`, which is how `map` over a plain closure stays nonthrowing since Swift 6.0.
  • How do you call a throws(ReadError) helper from a function declared throws(ImportError)?
    Catch and convert at the boundary: `do { try readFile() } catch { throw .unreadable(error) }`, where `error` is a `ReadError` and `.unreadable` is an `ImportError` case. A bare `try readFile()` fails with "thrown expression type 'ReadError' cannot be converted to error type 'ImportError'".

  • With typed throws, a catch for every enum case makes the do-catch exhaustive.
  • A closure that calls a typed-throws function is always inferred with that type.
  • Typed throws needs the Swift 6 language mode to compile.
  • A function declared throws(ParseError) can also let a ReadError escape.
  • Every throwing function should use typed throws for precision.

Assumes Swift 6.4; typed throws arrived in Swift 6.0 (SE-0413) and works in both Swift 5 and Swift 6 language modes, while full closure inference (FullTypedThrows) is still experimental.