In Swift, what does rethrows promise on a function that takes a closure, and what may its body throw?
answer
- throws only if an argument throws
- no try for a nonthrowing closure
- throw only inside a catch
- wrapping the closure's error
basics
~20 srethrows promises a function throws only when a function-typed argument throws, so a caller passing a nonthrowing closure needs no try. Its body may throw only inside a catch handling that parameter's error, for example to wrap it.
solid answer
~40 s`rethrows` marks a higher-order function as throwing only because its closure parameter can. The compiler checks this per call: pass a closure that cannot throw and the call needs no `try`; pass one that can and it needs `try`. The function must take at least one throwing function parameter, and a `throw` is legal only inside a `catch` that handles an error from such a parameter, which is how you translate a `ValidationError` into an `ImportError` at the boundary. `rethrows` is untyped, so callers see `any Error`. Since Swift 6.0 a generic `throws(E)` signature, which the standard library's `map` now uses, keeps the closure's concrete error type but cannot swap it for another.
code
swift · 28 linesenum ValidationError: Error { case badEmail(line: Int) }
enum ImportError: Error { case rowRejected(line: Int, underlying: any Error) }
struct Row { let line: Int; let email: String }
func validateEach(_ rows: [Row], _ check: (Row) throws -> Void) rethrows {
for row in rows {
do {
try check(row)
} catch {
throw ImportError.rowRejected(line: row.line, underlying: error) // allowed: inside catch
}
}
}
let rows = [Row(line: 2, email: "[email protected]"), Row(line: 3, email: "bob")]
validateEach(rows) { print($0.email) } // no try: this closure cannot throw
do {
try validateEach(rows) { row in
if !row.email.contains("@") { throw ValidationError.badEmail(line: row.line) }
}
} catch ImportError.rowRejected(let line, let underlying) {
print("line \(line): \(underlying)") // line 3: badEmail(line: 3)
} catch {
print("unexpected: \(error)")
}go deeper
Recall that rethrows appears on functions taking closures and means the call needs try only when the closure you pass can throw.
Explain the compiler's rules: a throwing function parameter is required, throw only inside catch, and the error seen by callers is any Error.
Show when you would wrap a closure's error at a stage boundary with rethrows, and when a generic throws(E) signature serves callers better.
Discuss how a library's higher-order APIs should carry errors, weighing error translation against preserving concrete types for callers.
## What rethrows promises A function declared **`rethrows`** says: "I throw only if one of my function-typed parameters throws." The compiler uses that promise at every call site: - If the closure you pass **cannot** throw, the call is treated as nonthrowing and needs no `try`. - If the closure **can** throw, the call is throwing and needs `try`, inside a `do`-`catch` or a throwing caller. This is what lets one higher-order function serve both kinds of caller. A CSV importer's `validateEach(_:_:)` can be called with a closure that only prints rows, with no ceremony, or with a validating closure that throws `ValidationError`, with `try`. ## Rules the compiler enforces The reference manual and Swift 6.4 agree on these rules: 1. A rethrowing function must have **at least one throwing function parameter**. `func noParam() rethrows {}` fails with "'rethrows' function must take a throwing function argument". 2. A `throw` statement may appear **only inside a `catch` clause**. A `throw` at the top of the body fails with "a function declared 'rethrows' may only throw if its parameter does". 3. That `catch` may handle only errors that came from one of the throwing **parameters**. If the `do` also calls some other throwing function, a `throw` in the `catch` is rejected, because the error might not have come from the closure. 4. `rethrows` is **untyped**. `rethrows(ValidationError)` fails with "'rethrows' cannot be combined with a specific thrown error type". Rule 2 is what makes error **translation** possible: the function may catch the closure's error and throw a different one in its place, as `validateEach` does when it wraps a `ValidationError` in `ImportError.rowRejected(line:underlying:)`. The promise still holds, because the new error is only ever thrown when the closure threw. ## Overriding and protocol conformance `rethrows` sits between nonthrowing and throwing: - A rethrowing method **can** override a throwing method and **can** satisfy a protocol requirement declared `throws`. - A throwing method **cannot** override a rethrowing method and **cannot** satisfy a `rethrows` requirement, because it would break the promise for callers passing nonthrowing closures. ## rethrows versus a generic throws(E) Swift 6.0 added typed throws (SE-0413), which gives a second way to write a pass-through function: make the closure's error type a generic parameter. ```swift func eachRow<E: Error>(_ rows: [Row], _ body: (Row) throws(E) -> Void) throws(E) { for row in rows { try body(row) } } ``` | | `rethrows` | generic `throws(E)` | |---|---|---| | Nonthrowing closure | call needs no `try` | `E` is inferred as `Never`, call needs no `try` | | Error type seen by caller | `any Error` | the closure's own `E` | | Throw a different error type | yes, from a `catch` | no, only values of `E` | | Restricts where the body may `throw` | yes, only inside a `catch` | no | Since Swift 6.0 the standard library's `Sequence.map` and `Collection.map` are declared `map<T, E>(_ transform: (Element) throws(E) -> T) throws(E) -> [T]`, which is why a `map` over a nonthrowing closure still needs no `try` and a typed closure keeps its error type. The reference manual notes the remaining difference: unlike `rethrows`, the generic form does not stop the function from throwing an `E` of its own. Pick `rethrows` when you want to replace or wrap the closure's error; pick `throws(E)` when you want callers to keep the concrete type. ## Reading the example In the snippet, the first call passes a closure that only prints, so the compiler treats `validateEach` as nonthrowing there and the call carries no `try`. The second closure throws `ValidationError.badEmail(line: 3)` for the row without an `@`. Inside `validateEach`, the `catch` receives that error and throws `ImportError.rowRejected(line: 3, underlying: ...)` in its place, which is legal because the `throw` sits in a `catch` that handled the parameter's error. The caller's first `catch` matches the wrapper case and prints `line 3: badEmail(line: 3)`. Because `rethrows` is untyped, the caller sees the error as `any Error`, so its chain still ends with a pattern-less `catch`. ## Common mistakes - Treating `rethrows` as "may throw its own errors", then adding a validation `throw` at the top of the body. - Expecting the caller to see the closure's concrete type; through `rethrows` it arrives as `any Error`. - Writing `try` on every call; it is required only when the passed closure can throw.
- Why does [1, 2].map { $0 * 2 } compile without try even though map accepts throwing closures?Since Swift 6.0 `map` is declared `map<T, E>(_ transform: (Element) throws(E) -> T) throws(E) -> [T]`. A closure that cannot throw makes `E` equal to `Never`, and a call that throws `Never` is nonthrowing. Before 6.0 the same effect came from `map` being `rethrows`.
- Can a rethrows method satisfy a protocol requirement declared throws, and the other way round?A rethrowing method can satisfy a `throws` requirement and can override a throwing method, because it never throws more than they allow. A plain throwing method cannot satisfy a `rethrows` requirement or override a rethrowing method, since callers passing nonthrowing closures rely on it not throwing.
- Can you write rethrows(ValidationError) to give a rethrowing function a concrete error type?No. Swift 6.4 rejects it with "'rethrows' cannot be combined with a specific thrown error type". To pass a concrete type through, make it generic: `func each<E: Error>(_ body: (Row) throws(E) -> Void) throws(E)`.
- A rethrows function may throw its own errors whenever it likes.
- Callers must always write try when they call a rethrows function.
- rethrows can be used on a function that has no closure parameters.
- Through rethrows the caller receives the closure's concrete error type.
- A throwing method can override a rethrowing method in a subclass.
Assumes Swift 6.4; the generic throws(E) alternative and the standard library's typed map arrived with typed throws in Swift 6.0 (SE-0413), while rethrows itself is unchanged.