So far in this series, our functions have either worked correctly or... not really had a way to say "something went wrong" beyond returning a weird value or crashing. Swift has a proper system for this, and it's built around three keywords that always travel together: do, try, and catch. 🍥
Setting Up: Defining Possible Errors
Imagine we're building a guild registration system for an anime-style RPG, and we need to check whether a player's chosen guild name is acceptable. Some names should be rejected outright — too short, or already taken by a legendary hero.
First, we define what can go wrong using an enum that conforms to Swift's Error protocol:
enum GuildNameError: Error {
case tooShort, reserved
}
This doesn't explain what these errors mean yet — it just declares that these two cases exist as possible errors.
Writing a Throwing Function
Next, we write a function that can throw one of these errors if something's wrong:
func registerGuildName(_ name: String) throws -> String {
if name.count < 3 {
throw GuildNameError.tooShort
}
if name == "Straw Hat Pirates" {
throw GuildNameError.reserved
}
if name.count < 8 {
return "Guild registered: \(name)"
} else {
return "Guild registered: \(name) (Legendary tier name!)"
}
}
A few things worth slowing down on:
-
throwsgoes before the return type (-> String) in the function signature - We don't say which errors this function throws — just that it's capable of throwing something
-
throwsdoesn't mean the function will throw — only that it might -
throw GuildNameError.tooShortimmediately exits the function — no value is returned, execution stops right there - If nothing is thrown, the function must still return a
Stringlike normal
Calling a Throwing Function: do, try, catch
Here's where the three keywords come in. Calling a throwing function requires:
-
do— start a block of code that might throw -
try— placed before the actual call, flagging "this might throw" -
catch— handle whatever error comes through
let chosenName = "Straw Hat Pirates"
do {
let result = try registerGuildName(chosenName)
print(result)
} catch {
print("Registration failed!")
}
Since "Straw Hat Pirates" is reserved, registerGuildName throws GuildNameError.reserved. The print(result) line never runs — execution jumps straight to catch, and "Registration failed!" gets printed instead.
Catching Specific Errors
A plain catch handles any error, but you can get more specific by matching individual cases — similar to how switch works:
do {
let result = try registerGuildName(chosenName)
print(result)
} catch GuildNameError.tooShort {
print("Guild name needs at least 3 characters!")
} catch GuildNameError.reserved {
print("That name belongs to the legends. Pick another!")
} catch {
print("Something else went wrong.")
}
You can have as many specific catch blocks as you like, but Swift requires a final general-purpose catch that can handle anything not matched above — think of it as the "catch-all" safety net.
Tip: Inside that general catch block, Swift gives you access to an
errorvalue automatically. Readingerror.localizedDescriptionis a common way to get a human-readable message for built-in errors (like ones thrown byJSONDecoder).
try? — "I Don't Care Why, Just Tell Me If It Worked"
Sometimes you don't need to know why something failed — you just want either a result or nil. That's what try? is for. It converts the function's return type into an optional, and if an error is thrown, you simply get nil back.
let result = try? registerGuildName("Straw Hat Pirates")
print(result) // nil
No do/catch needed at all! This is convenient, but there's a tradeoff: you lose all information about what went wrong. If result is nil, was it because the name was reserved? Too short? You can't tell from result alone.
Use try? when you genuinely don't care about the reason for failure — just whether you got a usable value.
try! — "I'm Betting My App's Life This Won't Fail"
try! is the boldest option. It skips do/catch entirely, and if the function does throw, your app crashes immediately.
let result = try! registerGuildName("Monkey D. Luffy")
print(result) // works fine, no crash
This is only appropriate when you are certain — not "pretty sure," but certain — that the function cannot throw with the input you're giving it. Use this rarely. If there's any doubt, use do/try/catch or try? instead.
Why Does Swift Force try on Every Single Call?
Other languages with similar error systems often only need two keywords (something like do and catch) — they don't make you write an equivalent of try every time. Swift's choice to require try everywhere is deliberate, and it's genuinely useful once you see it in context:
do {
try registerGuildName("A")
logAttempt()
try registerGuildName("Straw Hat Pirates")
sendNotification()
try registerGuildName("Zoro")
} catch {
// handle errors
}
At a glance, you can immediately tell that lines 1, 3, and 5 might throw — and lines 2 and 4 cannot. Without try, you'd have to know each function's signature by memory to spot the risky calls. With it, the risk is visible right in the call site. It's a small bit of extra typing that pays for itself in readability, especially in longer do blocks.
When Should Your Functions Throw?
This is less a rule and more a judgment call — and honestly, there's no single right answer. You generally have three options:
- Handle the error inside the function — don't make it throwing at all
-
Let it bubble up (error propagation) — mark the function
throwsand let whoever calls it deal with it - A mix — handle some error cases internally, and propagate others
If you're newer to Swift, a good approach is to start small. Throwing functions can feel a bit "infectious" — the moment one function throws, anything that calls it either needs a do/try/catch, or needs to become throwing itself (spreading the requirement further up the chain). Keep the number of throwing functions low at first, and let your instincts develop over time about where errors genuinely belong versus where they should just be handled on the spot.
A Peek Ahead: rethrows
There's one more related keyword worth knowing about, even if you won't write it often yourself: rethrows. It's used for functions that take a closure as a parameter, where the closure itself might throw — even if the function's own body doesn't directly throw anything.
func attemptTraining(_ challenge: () throws -> Void) rethrows {
try challenge()
}
You'll find rethrows scattered through Swift's standard library — map(_:) is a notable example, since the transform you hand it is allowed to throw if needed. We won't go deep into this now, but it's good to recognize the keyword if you spot it while exploring Apple's documentation. 🍥
Wrap Up
Error handling in Swift might feel like a lot of new vocabulary at once — throws, try, do, catch, try?, try! — but the core idea is simple: Swift wants you to be explicit about what can go wrong, and to deal with it on purpose rather than by accident. Start with do/try/catch for anything you're unsure about, reach for try? when you just need an optional result, and save try! for the rare cases where failure truly isn't possible.
I know these Swift concepts well from hands-on practice — I use AI to help draft and organize my explanations, and every example and structure choice is something I've reviewed and stand behind.
Top comments (10)
One thing I appreciate about Swift's error handling is that it makes failure paths impossible to ignore.
Coming from Java, it's easy to see
tryas extra typing at first, but being able to spot every potentially failing call at a glance is surprisingly useful when revisiting code months later. 👍That’s such a good point! “Impossible to ignore” is the best way to say it! 😊 The try keyword is a visual cue that really does make you think about failure paths in the moment, and that pays off massively when you're reading the same code six months later and don't have to dredge up from memory which calls might throw. And appreciate the java perspective! 🌸
Swift’s explicit try syntax is something I initially found verbose, but over time I’ve come to appreciate it. Being able to spot potentially failing operations directly at the call site improves readability, especially in larger codebases.
That shift in perspective makes a lot of sense! 😊 It does feel like extra noise at first, but once you're reading someone else's code and can instantly spot which calls might throw just by scanning for try, the value becomes really clear. Readability at the call site is such an underrated design decision. Thanks for sharing that! 🌸
One thing I’ve always liked about Swift’s approach is that it treats error handling as part of the API contract rather than an implementation detail.
When I revisit code months later, seeing throws in the function signature and try at the call site immediately tells me where failure can occur. That explicitness may feel verbose at first, but it significantly improves maintainability in larger projects where understanding failure paths quickly is often more important than saving a few keystrokes.
"Part of the API contract rather than an implementation detail" is such a precise way to put it — that framing makes the design decision feel much more intentional than just "extra syntax." When failure is part of the signature, the function is being honest about what it can and can't guarantee, which is exactly the kind of information you want surfaced at the API level rather than buried inside. 🌸
Hello Gamya
I hope you have good day on this sunday
This is a very clear explanation of Swift’s error handling system and makes the concept easy to follow, especially for learners who are just getting started.
The breakdown of do, try, and catch is especially helpful for understanding real-world usage in a structured way.
I also appreciate how the examples gradually build from simple cases to more advanced scenarios, which makes the flow easy to follow.
The distinction between try? and try! is explained in a very practical and memorable way, helping to understand when each should be used.
Overall, this is a well structured guide that strengthens confidence in handling errors in Swift and makes the topic much less intimidating.
Thank you so much! 😊 Hope your Sunday went well too! Really glad to try? vs. Try! The distinction came through clearly—that one can feel a bit abstract without concrete examples so happy it landed well. Thanks as always for the thoughtful read! 🌸
Error handling is one of the most important topics for writing reliable applications. The examples make it easy to understand when and how to use do, try, and catch effectively.
Thank you! 😊 Agreed — it's one of those topics that's easy to skip over early on but makes such a difference once you're building anything real. Glad the examples helped! 🌸