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

推荐订阅源

博客园 - 聂微东
D
Darknet – Hacking Tools, Hacker News & Cyber Security
P
Privacy International News Feed
NISL@THU
NISL@THU
Know Your Adversary
Know Your Adversary
G
GRAHAM CLULEY
The Hacker News
The Hacker News
P
Privacy & Cybersecurity Law Blog
S
Schneier on Security
T
Troy Hunt's Blog
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
S
Security Affairs
WordPress大学
WordPress大学
T
Tailwind CSS Blog
博客园 - Franky
T
The Exploit Database - CXSecurity.com
雷峰网
雷峰网
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
S
Securelist
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
有赞技术团队
有赞技术团队
爱范儿
爱范儿
Help Net Security
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 三生石上(FineUI控件)
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
阮一峰的网络日志
阮一峰的网络日志
C
Cybersecurity and Infrastructure Security Agency CISA
Spread Privacy
Spread Privacy
Last Week in AI
Last Week in AI
S
Security @ Cisco Blogs
博客园 - 司徒正美
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
罗磊的独立博客
博客园 - 叶小钗
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
J
Java Code Geeks
T
Threatpost
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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.