WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

When should you write throwing functions?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Throwing functions in Swift are those that are able to encounter errors they are unable or unwilling to handle. That doesn’t mean they will throw errors, just that it’s possible they can. As a result, Swift will make sure we’re careful when we use them, so that any errors that do occur are catered for.

But when you’re writing your code, chances are you’ll think to yourself “should this function throw any errors it encounters, or should it maybe handle them itself?” This is really common, and to be honest there is no single answer – you can handle the errors inside the function (thus making it not a throwing function), you can send them all back to whatever called the function (called “error propagation” or sometimes “bubbling up errors”), and you can even handle some errors in the function and send some back. All of those are valid solutions, and you will use all of them at some point.

When you’re just getting started, I would recommend you avoid throwing functions most of the time. They can feel a bit clumsy at first because you need to make sure all the errors are handled wherever you use the function, so it feels almost a bit “infectious” – suddenly you have errors needing to be handled in several places in your code, and if those errors bubble up further then the “infection” just spreads.

So, when you’re learning start small: keep the number of throwing functions low, and work outwards from there. Over time you’ll get a get better grip on managing errors to keep your program flow smooth, and you’ll feel more confident about adding throwing functions.

For a different perspective on throwing functions, see this blog post from Donny Wals: https://www.donnywals.com/working-with-throwing-functions-in-swift/

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.