Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 146 ยท Error Handling

Typed Throws

Learn Swift 6 typed throws: throws(MyError), exhaustive catch without a catch-all, converting errors, generic throws(E), Never, rethrows and when to use it.

Until Swift 6, every throwing function said only "I might throw something". The type of the error was erased to any Error. That made code easy to write, but it had a price: a catch clause could never be exhaustive without a catch-all, and callers had to guess which errors to expect from the documentation. If you added a new case, nothing in the compiler told you which switch statements needed an update.

Typed throws (SE-0413, Swift 6.0) lets a function name its error type: throws(ParseError). The compiler then knows exactly what can come out of a call, so catch blocks can be exhaustive over the enum, and generic code can say "I throw whatever your closure throws". This lesson builds on Error Handling and Custom Errors.

Declaring the error type

Put the type in parentheses after throws. Inside the function, throw .empty can use the short form because the compiler knows the type of the thrown value.

Swift throws(ParseError) and an exhaustive catch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints 12 and then not a number: zz. Look at the catch block: there is no catch let error as ParseError and no default. Every call inside the do block throws ParseError only, so Swift infers that the implicit error constant has type ParseError. If you later add a case to the enum, this switch stops compiling until you handle it, which is exactly the safety net exhaustive enums give you elsewhere.

A plain throws is shorthand for throws(any Error). A function with no throws is shorthand for throws(Never), which can never throw. These two ends and typed throws all fit into one system.

The type must match everything you throw

A function declared throws(ParseError) promises that nothing but ParseError leaves it. The compiler checks every throw and every try in its body.

Swift Throwing a different type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main.swift:5:40: error: thrown expression type 'OtherError' cannot be converted to error type 'ParseError'. Calling an untyped throwing function inside a typed one is rejected for the same reason: its errors are any Error, which could be anything.

Swift Calling an untyped throwing function (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Swift says error: thrown expression type 'any Error' cannot be converted to error type 'StepError'. You have two honest choices: widen the function to plain throws, or catch the untyped error and translate it (next section).

The reverse direction trips people up too. A catch after an untyped call still has error: any Error, so a pattern like .empty finds no member:

Swift Patterns on an untyped catch (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get error: type 'any Error' has no member 'empty'. The do block throws two different things (one ParseError, one any Error), so Swift widens the error to any Error. Remove the legacy() call, or add catch let error as ParseError, and it compiles.

Converting errors between layers

Typed throws pairs naturally with the layered design from the previous lesson. A lower layer throws its own enum, and the upper layer translates in a catch before rethrowing in its type. You can also annotate a do block with a type, do throws(E), when you want to state what the block can throw.

Swift Translating one error type into another

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first part prints save failed: the disk is full and the second typed do-block caught diskFull. Compare this with the untyped version, where save would need a catch-all and every caller would have to treat the result as any Error.

Generic error types and Never

The power of typed throws shows in generic code. A function can take a closure that throws some error E and itself throw the same E. This replaces rethrows with something more precise.

Swift throws(E): propagate whatever the closure throws

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is 4, caught negative, 1 and stack was empty. When the closure passed to apply cannot throw, E is inferred as Never, so the call is not marked with try at all. The compiler gets the same result as rethrows, but because the error type is a normal generic parameter, it also works when the closure does throw: the exact type flows through to the caller. The Stack example shows a pattern many types adopt: a nested Failure enum and catch .empty using the short pattern.

Never is an enum with no cases, so no value of it can exist. That is why throws(Never) means "cannot throw": you cannot even write a throw statement for it.

The standard library

Many standard library functions are typed-throws aware. Array.map and the Result { ... } initializer use throws(E), so that a typed closure produces a typed error.

Swift Typed errors through map and Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The map call throws at the third element, so the output begins typed: no. Then failure(binary.Bad.no), value 1 and true. The last line is the clearest benefit: the caught error is a Bad, so comparing it to .no compiles. With an untyped catch you would have to cast first.

Should you use it?

Typed throws is not "better throws". The Swift evolution proposal itself warns against adopting it everywhere. A good rule of thumb:

Use throws(E) when

  • the failures are a small closed set that is part of the function's purpose (a parser, a stack, a state machine);
  • you write generic code that must propagate the caller's error type (throws(E));
  • performance and code size matter and you cannot afford the allocation that boxing in any Error may need, as in Embedded Swift (see Embedded Swift);
  • the function and its callers live in the same module or package, so changing the type is not a breaking change.

Prefer plain throws when

  • it is a public library API that may gain new failure kinds. Adding a case to a typed enum, or changing the type, breaks callers;
  • errors come from many layers (file system, network, decoding) that you do not control, because a typed function would need a big wrapper enum;
  • you just need "something went wrong" with a message.

Many teams use typed throws inside a module and keep public API on plain throws. Also remember rethrows: it still works and is simpler when a function only forwards a closure's errors and you do not need to name them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of func f() throws(ParseError)?

    The compiler knows the exact error type, so the implicit error in a catch has that type and a switch over it can be exhaustive.
  2. 2. What does a function with no throws correspond to in the typed-throws model?

    A function that cannot throw has the error type Never, an enum with no cases.
  3. 3. What happens if you call an untyped throwing function inside a throws(StepError) function?

    An untyped call can throw anything. Catch and translate its error, or widen the function to plain throws.
  4. 4. In func apply<T, E: Error>(_ v: T, _ f: (T) throws(E) -> T) throws(E) -> T, what is E when the closure cannot throw?

    A non-throwing closure has the error type Never, so the call itself cannot throw and needs no try.
  5. 5. Why should public library APIs often stay on plain throws?

    A public typed error becomes part of the contract. New failure kinds then require a source-breaking change.

Summary

  • throws(MyError) names the error type; plain throws means throws(any Error) and no throws means throws(Never).
  • Inside a typed function every throw and try must produce that type, or the compiler reports cannot be converted to error type.
  • When every call in a do block throws the same type, catch gets a typed error and can be exhaustive.
  • Mixing in an untyped call widens the block back to any Error.
  • Translate errors between layers by catching one type and throwing another; use do throws(E) to state a block's type.
  • throws(E) with a generic E propagates a closure's error type exactly, and Never means no try is needed.
  • Use typed throws for closed, local failure sets and generic code; keep public APIs on plain throws unless the set is stable.

Next: The Result Type