Typed throws
suggest changeA plain throws function can throw any value that conforms to Error. The caller only sees any Error, so a catch block has to cast the error to a concrete type, and it always needs a final catch-all clause (see Catching different error types).
Swift 6.0 added typed throws. You write the error type in parentheses after throws:
func parseAge(_ s: String) throws(ParseError) -> Int
Now the compiler knows that parseAge can only throw a ParseError. Inside catch, error has the type ParseError, a switch over it can be exhaustive, and the function can't throw anything else by accident.
This article covers:
- declaring and catching typed errors
- how
throws,throws(any Error)andthrows(Never)relate - converting errors between layers
- generic functions that pass on the error type of a closure (
throws(E)instead ofrethrows) - the
Resulttype, which the typed-throws design builds on - when to stay with plain
throws
If you are new to Swift errors, start with Error handling basics and Throwing errors.
Typed throws needs Swift 6.0 or later, but it works in both the Swift 5 and Swift 6 language modes. Result has been around since Swift 5.0. The examples were compiled and run with Swift 6.4 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
Declaring a function with a typed error
The error type is usually an enum with one case per kind of failure:
enum ParseError: Error {
case empty
case notANumber(String)
case outOfRange(Int)
}
func parseAge(_ s: String) throws(ParseError) -> Int {
if s.isEmpty { throw .empty }
guard let n = Int(s) else { throw .notANumber(s) }
guard (0...150).contains(n) else { throw .outOfRange(n) }
return n
}
for input in ["42", "", "abc", "200"] {
do {
let age = try parseAge(input)
print("age:", age)
} catch {
// error has type ParseError, not any Error
switch error {
case .empty: print("empty input")
case .notANumber(let s): print("'\(s)' is not a number")
case .outOfRange(let n): print("\(n) is out of range")
}
}
}
Output:
age: 42
empty input
'abc' is not a number
200 is out of range
Notice three things:
throw .emptyworks without writingParseError.empty. The compiler knows the thrown type, so it infers the enum from context, like it does for a return value.- Every
tryin thedoblock calls a function that throwsParseError, so the compiler infers that the wholedoblock throwsParseError. The impliciterrorconstant incatchgets that type. - The
switchhas nodefault. It covers every case ofParseError, so it is exhaustive. If you add a case to the enum later, the compiler points at everyswitchthat must handle it.
With plain throws, the same catch block would need if let e = error as? ParseError followed by a fallback branch for errors that are "impossible" but that the compiler can't rule out.
Patterns in catch clauses
With a typed error you can put enum patterns straight into catch clauses, without the ParseError. prefix. This is handy when one or two cases need special handling and the rest share a generic path:
enum ParseError: Error {
case empty
case notANumber(String)
case outOfRange(Int)
}
func parseAge(_ s: String) throws(ParseError) -> Int {
if s.isEmpty { throw .empty }
guard let n = Int(s) else { throw .notANumber(s) }
guard (0...150).contains(n) else { throw .outOfRange(n) }
return n
}
func describe(_ input: String) -> String {
do {
return "age \(try parseAge(input))"
} catch .outOfRange(let n) {
return "\(n) is out of range"
} catch {
// error is still a ParseError here
return "invalid input: \(error)"
}
}
for input in ["30", "", "-5", "abc"] {
print(describe(input))
}
Output:
age 30
invalid input: empty
-5 is out of range
invalid input: notANumber("abc")
In the last catch, error still has the type ParseError, so you can switch over it or pass it on as a ParseError.
The compiler does not check a list of catch clauses for exhaustiveness, though (as of Swift 6.4). Even if the patterns name every case, a non-throwing function still needs a final catch-all clause:
func describe(_ input: String) -> String {
do {
return "age \(try parseAge(input))"
} catch .empty {
return "empty input"
} catch .notANumber(let s) {
return "'\(s)' is not a number"
} catch .outOfRange(let n) {
return "\(n) is out of range"
}
}
error: errors thrown from here are not handled because the enclosing catch is not exhaustive
To get exhaustiveness checking, use one catch with a switch inside, as in the previous section. Top-level code in main.swift doesn't show this error, because top-level code is allowed to throw, and an unhandled error there stops the program at run time.
Compare this with the catch and switch pattern for untyped errors, where the switch itself also needs a default.
The compiler checks what you throw
A typed function can't throw a different error type:
enum ParseError: Error { case empty }
struct OtherError: Error {}
func parse(_ s: String) throws(ParseError) -> Int {
if s == "?" { throw OtherError() }
return 0
}
error: thrown expression type 'OtherError' cannot be converted to error type 'ParseError'
The same check applies to errors that come from calls. Here read() throws IOError, and both() promises to throw only ParseError:
enum ParseError: Error { case empty }
enum IOError: Error { case missing }
func parse() throws(ParseError) -> Int { 1 }
func read() throws(IOError) -> String { "" }
func both() throws(ParseError) {
_ = try parse()
_ = try read()
}
error: thrown expression type 'IOError' cannot be converted to error type 'ParseError'
A function can throw only one error type. There is no throws(ParseError | IOError). When a do block calls functions with different error types, the compiler falls back to any Error for that block:
do {
_ = try parse()
_ = try read()
} catch {
switch error {
case .empty: print("x")
}
}
error: type 'any Error' has no member 'empty'
To keep the error typed across several sources, wrap them in an enum of your own. That's the next section.
You can also state the thrown type of a do block explicitly with do throws(ParseError) { ... }. Then the compiler reports an error if anything inside the block throws a different type, instead of quietly falling back to any Error.
Converting errors between layers
A common setup is a low-level function that throws IOError, another that throws ParseError, and a higher-level function that combines them. The higher-level function defines its own error type with a case for each source, and converts errors in a catch:
enum ParseError: Error { case empty, notANumber(String) }
enum IOError: Error { case fileNotFound(String) }
enum ConfigError: Error {
case io(IOError)
case parse(ParseError, line: Int)
}
let files = ["app.conf": "8080\n\nabc"]
func readFile(_ name: String) throws(IOError) -> String {
guard let text = files[name] else { throw .fileNotFound(name) }
return text
}
func parseInt(_ s: String) throws(ParseError) -> Int {
if s.isEmpty { throw .empty }
guard let n = Int(s) else { throw .notANumber(s) }
return n
}
func loadNumbers(_ name: String) throws(ConfigError) -> [Int] {
let text: String
do {
text = try readFile(name)
} catch {
throw .io(error)
}
var result: [Int] = []
for (i, line) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
do {
result.append(try parseInt(String(line)))
} catch {
throw .parse(error, line: i + 1)
}
}
return result
}
for name in ["app.conf", "missing.conf"] {
do {
print(try loadNumbers(name))
} catch {
switch error {
case .io(.fileNotFound(let f)): print("no such file:", f)
case .parse(let e, let line): print("line \(line): \(e)")
}
}
}
Output:
line 2: empty
no such file: missing.conf
In catch { throw .io(error) }, error is an IOError, so it fits the io case directly. The caller of loadNumbers sees a single type, and the nested pattern .io(.fileNotFound(let f)) matches straight through both levels.
Converting in this way also adds context: the parse case records the line number, which parseInt knows nothing about.
throws, throws(any Error) and throws(Never)
Typed throws makes the old forms special cases of the new one:
throwsmeansthrows(any Error)- a function without
throwsbehaves likethrows(Never)
Never is an enum with no cases, so no value of it can ever be created and nothing can be thrown:
func untyped() throws -> Int { 1 }
func typedAny() throws(any Error) -> Int { 2 }
func cannotFail() throws(Never) -> Int { 3 }
let f: () throws -> Int = typedAny
let g: () throws(any Error) -> Int = untyped
print(type(of: f), type(of: g))
// throws(Never) is a non-throwing function: no `try` needed
let n = cannotFail()
print(n)
let h: () -> Int = cannotFail
print(type(of: h))
Output:
() throws -> Int () throws -> Int
3
() -> Int
You'd rarely write throws(Never) by hand. It matters for generic code: when a generic error type E turns out to be Never, the function becomes non-throwing and callers don't need try.
Typed errors also convert to any Error freely. An untyped function can call a typed one, and the error is boxed as any Error when it leaves.
Generic error propagation: rethrows vs throws(E)
Before Swift 6.0, a function that takes a closure used rethrows to say "I only throw if the closure throws". The error still came out as any Error, even when the closure could only throw one type.
With typed throws, the error type becomes a generic parameter. The function throws exactly what the closure throws:
enum ParseError: Error { case notANumber(String) }
// Old style: rethrows. Throws only if `body` throws, but always as `any Error`.
func retry<T>(times: Int, _ body: () throws -> T) rethrows -> T {
for _ in 1..<times {
if let value = try? body() { return value }
}
return try body()
}
// New style: the thrown type is a generic parameter.
func retryTyped<T, E: Error>(times: Int, _ body: () throws(E) -> T) throws(E) -> T {
for _ in 1..<times {
if let value = try? body() { return value }
}
return try body()
}
final class Flaky {
var attempts = 0
func next() throws(ParseError) -> Int {
attempts += 1
if attempts < 3 { throw .notANumber("try \(attempts)") }
return 42
}
}
// No closure throws: no `try` needed in either version (E is inferred as Never).
print(retry(times: 2) { 1 })
print(retryTyped(times: 2) { 1 })
do {
let flaky = Flaky()
print(try retryTyped(times: 2, flaky.next))
} catch {
// error is ParseError here; with retry() it would be any Error
switch error {
case .notANumber(let s): print("gave up after", s)
}
}
let flaky = Flaky()
print(try! retryTyped(times: 5, flaky.next), "after", flaky.attempts, "attempts")
Output:
1
1
gave up after try 2
42 after 3 attempts
throws(E) covers everything rethrows does:
- a non-throwing closure makes
Eequal toNever, so the call needs notry - an untyped closure makes
Eequal toany Error - a typed closure keeps its type
Since Swift 6.0, the standard library uses this for many closure-taking functions, including map on sequences and optionals, Result.init(catching:) and Mutex.withLock (see Mutex and Atomic with the Synchronization module).
Closures don't infer a typed error
There is one catch. A closure's thrown type is not inferred from its body. A closure with try in it is treated as throwing any Error, even if every call inside throws ParseError. To keep the type, pass a function reference, or write the thrown type in the closure signature:
enum ParseError: Error { case empty, notANumber(String) }
func parse(_ s: String) throws(ParseError) -> Int {
if s.isEmpty { throw .empty }
guard let n = Int(s) else { throw .notANumber(s) }
return n
}
func report(_ e: ParseError) { print("ParseError:", e) }
let inputs = ["1", "2", "x"]
// Passing the function directly keeps its type
do {
print(try inputs.map(parse))
} catch {
report(error)
}
// A closure needs the thrown type written out
do {
print(try inputs.map { s throws(ParseError) in try parse(s) * 10 })
} catch {
report(error)
}
// Non-throwing closure: map() doesn't throw, no try needed
print(inputs.map { $0.count })
Output:
ParseError: notANumber("x")
ParseError: notANumber("x")
[1, 1, 1]
Without the annotation the error is any Error:
do {
print(try inputs.map { try parse($0) * 10 })
} catch {
report(error)
}
error: cannot convert value of type 'any Error' to expected argument type 'ParseError'
Typed throws with async functions and protocols
async functions can use typed throws too. Write async throws(E):
enum FetchError: Error {
case timeout
case status(Int)
}
func fetch(_ path: String) async throws(FetchError) -> String {
try? await Task.sleep(for: .milliseconds(10))
switch path {
case "/slow": throw .timeout
case "/missing": throw .status(404)
default: return "content of \(path)"
}
}
protocol Loader {
associatedtype LoadError: Error
func load(_ key: String) throws(LoadError) -> String
}
struct MemoryLoader: Loader {
let data: [String: String]
func load(_ key: String) throws(FetchError) -> String {
guard let v = data[key] else { throw .status(404) }
return v
}
}
struct ConstantLoader: Loader {
func load(_ key: String) -> String { "always \(key)" }
}
func describe<L: Loader>(_ loader: L, _ key: String) -> String {
do {
return try loader.load(key)
} catch {
return "failed: \(error)"
}
}
for path in ["/home", "/slow", "/missing"] {
do {
print(try await fetch(path))
} catch {
switch error {
case .timeout: print(path, "timed out")
case .status(let code): print(path, "returned", code)
}
}
}
print(describe(MemoryLoader(data: ["a": "1"]), "a"))
print(describe(MemoryLoader(data: [:]), "b"))
print(describe(ConstantLoader(), "c"))
print(ConstantLoader.LoadError.self)
Output:
content of /home
/slow timed out
/missing returned 404
1
failed: status(404)
always c
Never
The Loader protocol uses an associated type for the error. Each conforming type picks its own. ConstantLoader.load doesn't throw at all, so the compiler infers LoadError as Never.
The standard library's AsyncSequence uses the same idea with its Failure associated type. See AsyncSequence, AsyncStream and continuations for an iterator whose next() is async throws(APIError). To learn more about async functions in general, see async and await.
Result: errors as values
Result<Success, Failure> is an enum with two cases, .success(Success) and .failure(Failure), where Failure: Error. It has always had a typed error. Typed throws gives the same precision to functions that throw.
Result is useful when you need to store an error or pass it around as a value instead of throwing right away. Examples are a completion handler, a cache of past outcomes, or a list of results where some items failed.
enum ParseError: Error {
case empty
case notANumber(String)
}
func parseInt(_ s: String) throws(ParseError) -> Int {
if s.isEmpty { throw .empty }
guard let n = Int(s) else { throw .notANumber(s) }
return n
}
// Creating results directly
let ok: Result<Int, ParseError> = .success(10)
let bad: Result<Int, ParseError> = .failure(.empty)
// Wrapping a throwing call. Annotate the closure, or the failure becomes any Error.
let r1 = Result { () throws(ParseError) in try parseInt("21") }
let r2 = Result { () throws(ParseError) in try parseInt("x") }
let r3 = Result { try parseInt("x") }
print(r1)
print(r2)
print(type(of: r3))
// Inspecting with switch
for r in [ok, bad, r1, r2] {
switch r {
case .success(let n): print("got", n)
case .failure(.empty): print("empty")
case .failure(.notANumber(let s)): print("bad:", s)
}
}
// Back to throwing: get() rethrows the typed failure
do {
let n = try r2.get()
print(n)
} catch {
print("get() threw", error) // error is ParseError
}
// Transforming
let doubled = r1.map { $0 * 2 }
print(doubled)
struct AppError: Error { let message: String }
let wrapped = r2.mapError { e in AppError(message: "parse failed: \(e)") }
print(wrapped)
let sum = r1.flatMap { a in
Result { () throws(ParseError) in try parseInt("5") }.map { b in a + b }
}
print(sum)
let r4: Result<Int, any Error> = r2.mapError { $0 }
print(type(of: r4))
Output:
success(21)
failure(main.ParseError.notANumber("x"))
Result<Int, Error>
got 10
empty
got 21
bad: x
get() threw notANumber("x")
success(42)
failure(main.AppError(message: "parse failed: notANumber(\"x\")"))
success(26)
Result<Int, Error>
The main operations:
Result { try ... }(that is,init(catching:)) runs a throwing closure and captures either the value or the error. Because of the closure rule above,r3has the typeResult<Int, any Error>. Annotate the closure withthrows(ParseError)to keep the type.get()turns aResultback into a throwing call. OnResult<Int, ParseError>, it isthrows(ParseError), sotry r.get()fits into typed-throws code.maptransforms the success value and leaves a failure untouched.mapErrortransforms the failure, for example to wrap it in a higher-level error type, or to erase it toany Error.flatMapchains a step that itself returns aResult.flatMapErrordoes the same for failures.switchwith nested patterns like.failure(.notANumber(let s))handles each case exhaustively.
In new code, async throws(E) usually replaces completion handlers that take a Result, and Result remains for the cases where an outcome must be stored.
When to stay untyped
Typed throws is not a replacement for throws everywhere. The Swift authors recommend plain throws for most code. Typed throws fits these cases:
- Errors the caller handles case by case. A parser, a validator or a state machine whose callers really do
switchover every failure. - Generic code that forwards a closure's error.
throws(E)is better thanrethrows, because it keeps the type and turns into a non-throwing function whenEisNever. - Module-internal or private code, where you control every caller and can change the error type freely.
- Performance-sensitive or Embedded Swift code.
any Erroris a box that may need a heap allocation. A concrete error type doesn't, which is why Embedded Swift code, which avoids existentials, relies on typed throws.
Stay with plain throws when:
- The function calls into code with many unrelated error types, such as file I/O, networking and decoding. Wrapping each of them in your own enum adds a lot of code and often only hides the original error.
- The function is public API in a library. The error type becomes part of the signature. Adding a case to a public enum, or changing the type later, breaks callers who switch exhaustively over it.
- Callers just log or display the error. They don't gain anything from a concrete type.
You can mix both styles freely. A typed error converts to any Error as soon as it reaches an untyped function, so a typed helper can sit inside an untyped API.
Summary
func f() throws(E)declares the only error typefcan throw.throw .someCaseinfers the type.- In
catch,errorhas the concrete type, so aswitchover it can be exhaustive with nodefault. A list ofcatchpatterns is not checked for exhaustiveness and still needs a finalcatch. throwsisthrows(any Error), and non-throwing isthrows(Never).- A function throws exactly one type. Combine several with an enum of your own, and convert in
catch { throw .wrapper(error) }. - In generic code, write
<E: Error>(_ body: () throws(E) -> T) throws(E)instead ofrethrows. - Closures don't infer a typed error from their body. Write
{ x throws(E) in ... }or pass a function reference. Result<Success, Failure>stores an outcome as a value.get()throws its typed failure.map,mapErrorandflatMaptransform it.- Use typed throws for small, closed error sets that callers handle case by case. Use plain
throwsfor public APIs and for code with many unrelated error sources.