How do I use typed throws?

Asked on 09/30/2024

1 search

To use typed throws in Swift, you specify the error type along with the throws keyword. This feature allows you to handle error types in a more generic way without type erasure, meaning the error appears in the catch block with its concrete type. Typed throws is a generalization of the error handling system, where untyped throws are equivalent to typed throws with an Any error type, and a non-throwing function is equivalent to a function with a typed throw of the Never type.

Typed throws can be particularly useful when working with internal functions or functions that propagate the error from their arguments, or in constrained environments where untyped throws are cost-prohibitive. However, if you want to maintain flexibility to change the thrown error type, you should continue using untyped throws.

For more details, you can refer to the session What’s new in Swift (23:34).

How do I use typed throws? | Ask WWDC