惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
月光博客
月光博客
博客园 - Franky
Martin Fowler
Martin Fowler
U
Unit 42
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
The Cloudflare Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
J
Java Code Geeks
B
Blog RSS Feed
博客园 - 三生石上(FineUI控件)
MongoDB | Blog
MongoDB | Blog
腾讯CDC
博客园_首页
博客园 - 司徒正美
D
DataBreaches.Net
I
InfoQ
GbyAI
GbyAI
IT之家
IT之家
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Swift Functions — Handling Errors with do, try, and catch 🚨
Gamya · 2026-06-20 · via DEV Community

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:

  • throws goes 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
  • throws doesn't mean the function will throw — only that it might
  • throw GuildNameError.tooShort immediately exits the function — no value is returned, execution stops right there
  • If nothing is thrown, the function must still return a String like normal

Calling a Throwing Function: do, try, catch

Here's where the three keywords come in. Calling a throwing function requires:

  1. do — start a block of code that might throw
  2. try — placed before the actual call, flagging "this might throw"
  3. 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 error value automatically. Reading error.localizedDescription is a common way to get a human-readable message for built-in errors (like ones thrown by JSONDecoder).

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:

  1. Handle the error inside the function — don't make it throwing at all
  2. Let it bubble up (error propagation) — mark the function throws and let whoever calls it deal with it
  3. 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.