How do I use typed throws?

Generated on 9/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).

What’s new in Swift

What’s new in Swift

Join us for an update on Swift. We’ll briefly go through a history of Swift over the past decade, and show you how the community has grown through workgroups, expanded the package ecosystem, and increased platform support. We’ll introduce you to a new language mode that achieves data-race safety by default, and a language subset that lets you run Swift on highly constrained systems. We’ll also explore some language updates including noncopyable types, typed throws, and improved C++ interoperability.

Go further with Swift Testing

Go further with Swift Testing

Learn how to write a sweet set of (test) suites using Swift Testing’s baked-in features. Discover how to take the building blocks further and use them to help expand tests to cover more scenarios, organize your tests across different suites, and optimize your tests to run in parallel.

A Swift Tour: Explore Swift’s features and design

A Swift Tour: Explore Swift’s features and design

Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.

Xcode essentials

Xcode essentials

Edit, debug, commit, repeat. Explore the suite of tools in Xcode that help you iterate quickly when developing apps. Discover tips and tricks to help optimize and boost your development workflow.