The Analogy: The Parcel Returns Depot
Picture the sorting floor of a parcel depot. A parcel travels down a belt past a line of workers, each performing one step: scan the barcode, print a label, weigh it, load it onto the right truck. When a worker cannot do their step -- the barcode is smudged, the address is nonsense -- they do not guess and they do not silently shove it along. They clip a bright red reason tag to it stating exactly what is wrong, and they set the parcel onto a separate exceptions belt that carries it away from the main line. Attaching that tag and diverting the parcel is a throw: the worker reports a specific failure instead of returning a normal result.
The exceptions belt runs up to a supervisor's desk. The supervisor reads each red tag and routes the parcel by reason: a bad address goes to the address desk, a damaged box goes to repacking, and anything unrecognised goes to the floor manager. That triage station is a do/catch block. Each specific destination is a typed catch that matches one reason and binds its details; the floor manager who takes whatever is left over is the general catch that handles any error the specific clauses did not. A worker who is merely allowed to use the exceptions belt -- rather than one who must resolve every problem alone -- is a function marked throws: it may report a failure upward for someone else to handle.
Not every response to a snag is a full red tag. A worker told "if the label printer jams, just drop this parcel in the recycle slot and hand me an empty tray" is using try-question-mark: a failure becomes a quiet nil rather than a routed exception. A worker who stamps "I personally certify this parcel is flawless, and if I am wrong you may shut down the entire depot" is using try-bang: fine when the certainty is real, catastrophic when it is not. And sometimes the depot does not act on a problem immediately at all -- it seals the outcome inside a clipboard that holds either a delivery receipt or the red tag, to be opened later by whoever is ready. That sealed clipboard is a Result value: the success and the failure travel together until someone chooses to look.
The failure mode is the worker who, to keep their belt moving and their numbers high, quietly tosses every questionable parcel straight into the trash -- no tag, no exceptions belt, no record. The line looks fast and spotless, and for a while nobody notices. Then customers begin calling about parcels that never arrived, and there is nothing to tell them: no reason, no location, no trace of where or why each one was lost. That is what swallowing errors does. Wrapping everything in try-question-mark or leaving an empty catch block silences the exact diagnostic information the whole error-handling system exists to preserve, and the failures do not stop happening -- they just stop being visible until they are far more expensive to investigate.
Syntax or Core Structure
Swift's error model has four moving parts: a type that describes what can go wrong, a function that is allowed to fail, the site that calls it, and the cleanup that must happen regardless. Read them together before taking each apart.
// 1. An error type: usually an enum, always conforming to Error.
enum FuelError: Error {
case empty
case contaminated(percent: Int)
}
// 2. A throwing function: it may report failure instead of returning.
func burn(litres: Int, tank: Int) throws -> Int {
guard tank > 0 else { throw FuelError.empty }
return tank - litres
}
// 3. The call site: try inside a do, with catch clauses to triage.
func run() {
defer { print("engine cooled") } // 4. always runs on the way out
do {
let left = try burn(litres: 3, tank: 10)
print("remaining: \(left)")
} catch FuelError.empty {
print("tank is empty")
} catch {
print("other: \(error)")
}
}
// try? turns a throw into nil; try! turns a throw into a crash.
let maybe = try? burn(litres: 3, tank: 0) // nil
// Result stores success or failure to inspect later.
let outcome: Result<Int, FuelError> = .success(7)
The enum names each failure with the data needed to react; throws marks the function as a worker allowed to divert onto the exceptions belt; try at the call site acknowledges that the next expression might fail; catch clauses match by type and are tried top to bottom; defer schedules cleanup that runs on every exit path. try?, try!, and Result are the three alternatives to a full do/catch, each trading away some information for some convenience.
Technical Depth: How Swift Reports and Recovers
Throwing and catching by type
A catch clause is a filter: it matches errors of a particular case or type and binds their associated values, and clauses are tried in written order until one matches. Put the specific reasons first and a bare catch last, so the depot routes each parcel to the right desk before it reaches the floor manager.
| Clause | Matches | Binds |
|---|---|---|
| catch MyError.timeout | exactly that one case | nothing |
| catch MyError.tooBig(let n) | that case | its associated value n |
| catch let e as MyError | any case of MyError | the whole error as e |
| catch | anything left | the value as the implicit error |
enum WithdrawalError: Error {
case insufficientFunds(balance: Int, requested: Int)
}
func withdraw(_ amount: Int, from balance: Int) throws -> Int {
guard amount <= balance else {
throw WithdrawalError.insufficientFunds(balance: balance, requested: amount)
}
return balance - amount
}
func report(_ amount: Int, from balance: Int) {
do {
let left = try withdraw(amount, from: balance)
print("ok, remaining: \(left)")
} catch WithdrawalError.insufficientFunds(let have, let want) {
print("declined: need \(want), have \(have)")
} catch {
print("other: \(error)")
}
}
report(30, from: 100)
report(150, from: 100)
The first call succeeds and prints the remaining balance. The second throws, the specific clause matches and binds both associated values, and the general catch is never reached. Because the clause pattern-matches the enum case rather than a text message, renaming the error's description later would not break this routing.
Output:
ok, remaining: 70
declined: need 150, have 100
try, try-question-mark, and try-bang: three ways to face a throw
The same throwing call can be approached three ways, and the choice decides how much you learn when it fails. Plain try inside a do keeps the full error and routes it to a catch. try? throws that information away and hands back nil. try! asserts the call cannot fail and crashes the process if it does.
| Form | On success | On throw |
|---|---|---|
| try (inside do) | returns the value | jumps to a catch clause |
| try? | wraps the value in an optional | evaluates to nil |
| try! | returns the value | crashes the program |
enum ParseError: Error { case notANumber(String) }
func toInt(_ text: String) throws -> Int {
guard let n = Int(text) else { throw ParseError.notANumber(text) }
return n
}
do {
let n = try toInt("42")
print("parsed: \(n)")
} catch {
print("failed")
}
let bad = try? toInt("nope") // throws -> nil
print("bad: \(bad ?? -1)")
let good = try? toInt("7") // succeeds -> Optional(7)
print("good: \(good ?? -1)")
let sure = try! toInt("100") // certain to succeed here
print("sure: \(sure)")
The do block parses cleanly and prints the value. try? toInt("nope") fails and collapses to nil, so the ?? -1 fallback prints -1; the reason ("nope" was not a number) is gone. try? toInt("7") succeeds and yields Optional(7). The try! call is safe only because the literal "100" provably parses; on a real input it would be a crash waiting to happen.
Output:
parsed: 42
bad: -1
good: 7
sure: 100
Result: an error you can pass around
A throw must be handled at the call site, right then. Sometimes you want to produce the outcome now and inspect it later, or store a mix of successes and failures in an array. Result<Success, Failure> is that sealed clipboard: a value that is either .success(value) or .failure(error), examined with a switch when you are ready. Its map transforms only the success branch and leaves a failure untouched.
enum DivError: Error { case divideByZero }
func divide(_ a: Int, by b: Int) -> Result<Int, DivError> {
guard b != 0 else { return .failure(.divideByZero) }
return .success(a / b)
}
let batch = [divide(10, by: 2), divide(7, by: 0), divide(20, by: 4)]
for r in batch {
switch r {
case .success(let q): print("= \(q)")
case .failure(let e): print("err: \(e)")
}
}
let doubled = divide(9, by: 3).map { $0 * 2 } // .success(6)
if case .success(let v) = doubled {
print("doubled: \(v)")
}
The three divisions are computed up front and stored together; iterating the array unpacks each with a switch, so the failed 7 / 0 sits alongside the two successes without stopping the loop. The final map runs $0 * 2 only because divide(9, by: 3) succeeded with 3, giving .success(6); had it been a failure, map would have passed the error through unchanged.
Output:
= 5
err: divideByZero
= 5
doubled: 6
defer: cleanup that always runs
Acquiring a resource creates an obligation to release it, and a throw partway through must not skip that release. A defer block registers cleanup the moment you acquire, and Swift runs it on every exit from the scope -- normal return, early return, or thrown error. Multiple defer blocks in one scope run in reverse order, last registered first.
| Exit path | Does defer run? |
|---|---|
| reaching the end normally | yes |
| an early return | yes |
| a thrown error leaving the scope | yes |
| a crash from try! or fatalError | no |
func process(_ steps: [String]) {
print("open resource")
defer { print("close resource") } // runs however we leave
for step in steps {
if step == "stop" {
print("stopping early")
return
}
print("do: \(step)")
}
print("all steps done")
}
process(["a", "b"])
print("--")
process(["a", "stop", "c"])
The first run walks every step to the end, then the deferred cleanup fires last. The second run hits "stop", returns early, and skips the "c" step and the "all steps done" line -- yet "close resource" still prints, because the defer is bound to the scope, not to any one exit. That guarantee is why defer is the right home for closing files and releasing locks even in code that throws.
Output:
open resource
do: a
do: b
all steps done
close resource
--
open resource
do: a
stopping early
close resource
Real World Example: A Config File Loader
Reading a small key=value configuration is a compact showcase for the whole model: a typed error that names each way parsing can fail, a throwing initializer and a throwing lookup, a do/catch that triages by reason, and a defer that reports completion no matter which path runs. The parser splits the text into lines, rejects anything that is not exactly one key and one value, and looks keys up on demand.
enum ConfigError: Error, CustomStringConvertible {
case emptySource
case malformedLine(Int, String)
case missingKey(String)
var description: String {
switch self {
case .emptySource:
return "config is empty"
case .malformedLine(let n, let text):
return "line \(n) is malformed: '\(text)'"
case .missingKey(let key):
return "required key missing: \(key)"
}
}
}
struct Config {
private var values: [String: String]
init(from source: String) throws {
let lines = source
.split(separator: "\n", omittingEmptySubsequences: true)
.map { String($0) }
guard !lines.isEmpty else { throw ConfigError.emptySource }
var parsed: [String: String] = [:]
for (index, line) in lines.enumerated() {
let parts = line.split(separator: "=", maxSplits: 1).map { String($0) }
guard parts.count == 2 else {
throw ConfigError.malformedLine(index + 1, line)
}
parsed[parts[0]] = parts[1]
}
self.values = parsed
}
func require(_ key: String) throws -> String {
guard let value = values[key] else { throw ConfigError.missingKey(key) }
return value
}
}
func loadSettings(_ text: String) {
print("loading config")
defer { print("done loading") }
do {
let config = try Config(from: text)
let host = try config.require("host")
let port = try config.require("port")
print("host=\(host) port=\(port)")
} catch let error as ConfigError {
print("config error: \(error)")
} catch {
print("unexpected: \(error)")
}
}
let good = "host=localhost\nport=8080"
let missing = "host=localhost"
let broken = "host=localhost\nport"
loadSettings(good)
print("--")
loadSettings(missing)
print("--")
loadSettings(broken)
Output:
loading config
host=localhost port=8080
done loading
--
loading config
config error: required key missing: port
done loading
--
loading config
config error: line 2 is malformed: 'port'
done loading
The good source has two well-formed lines, so the initializer builds a two-entry dictionary, both require calls find their keys, and the settings line prints before the deferred "done loading". Notice the lookups read values["host"] and values["port"] by explicit key, so nothing depends on dictionary iteration order -- the output is fully determined.
The missing source parses fine but has no port, so require("port") throws missingKey("port"); the catch let error as ConfigError clause matches, prints the plain-language reason, and the defer still fires. The broken source has a second line port with no =, so split(separator: "=", maxSplits: 1) yields a single part, the guard parts.count == 2 fails, and the initializer throws malformedLine(2, "port") before any dictionary is built. Each failure is reported with the specific reason the depot's tag would carry, and in every case the cleanup line runs.
The design leans on the pieces this lesson introduced: one typed enum enumerates every failure mode with the context needed to describe it, the throwing initializer refuses to construct a half-valid Config, and defer guarantees the completion notice regardless of which branch is taken. Conforming ConfigError to CustomStringConvertible means \(error) prints the friendly message instead of a raw case name.
The genuine flaw is that loadSettings swallows every error after printing it and returns Void, so a caller cannot tell a fully loaded config from one that failed -- the program marches on with no settings and no signal to stop, which is exactly the "quietly trash the parcel" failure from the analogy, only politely logged. A second, quieter bug hides in the parser: because split uses omittingEmptySubsequences by default, a legitimate key= line with an intentionally empty value collapses to one part and is wrongly rejected as malformed. The fix on both counts is to stop swallowing and stop guessing: have loadSettings return Result<Config, ConfigError> (or mark it throws) so the caller decides what to do, and split each line on the first = by index rather than discarding empty pieces, so an empty value is preserved instead of misreported.
Common Mistakes
- Swallowing errors silently: A blanket
try?or an emptycatch {}discards the reason a step failed and leaves no trace. Log it, handle it, or propagate it -- never let a failure vanish without a record. - Reaching for try-bang by default:
try!crashes the whole program on any throw. Reserve it for values you can prove cannot fail, such as a hard-coded literal, and never for network responses or user input. - Ordering a general catch before specific ones:
catchclauses match top to bottom, so an untypedcatchor a broadcatch let e as BaseErrorplaced first shadows every specific clause below it. List the narrow cases first. - Forgetting to propagate throws: A function that calls a throwing function must either handle the error or be marked
throwsitself. Wrapping the call intry?only to silence the compiler usually buries a real failure. - Matching errors by their text: Comparing
error.localizedDescriptionagainst a string is brittle and breaks the moment the wording changes. Pattern-match the enum case (catch MyError.timeout) so the logic keys off structure, not prose. - Skipping defer for cleanup: Without
defer, an earlythrowleaves files, locks, and connections open. Register the release withdeferon the line right after you acquire the resource. - Mixing Result and throws haphazardly: Converting back and forth --
try result.get()then re-wrapping in anotherResult-- muddies the flow. Usethrowsfor immediate call sites andResultwhen the outcome must be stored, passed, or inspected later. - Using stringly or untyped error codes: A typed
enum ...: Errorwith associated values documents every failure mode and letscatchbind the details. Integer codes or bare strings throw that structure away. - Collapsing distinct failures into one nil:
try? step() ?? fallbacktreats "not found", "timeout", and "malformed" as the same non-answer. When the caller needs to react differently to each, keep the typed error rather than flattening it to an optional.
Best Practices
- Model failures as typed enums: An
enum ...: Errorwith one case per failure mode, each carrying the context needed to react, turns error handling into ordinary exhaustive pattern matching. - Adopt LocalizedError for human-facing text: Implement
errorDescriptionwhen a message will reach a user or a log, so the wording lives with the error rather than being reinvented at each call site. - Pair every acquire with a defer: Register cleanup immediately after obtaining a resource. It runs on the normal path, the early return, and the throwing path alike, which is exactly when leaks otherwise happen.
- Throw for now, Result for later: Prefer throwing functions at synchronous call sites where the caller reacts immediately; reach for
Resultwhen the outcome must be stored, collected, or handed to another layer before inspection. - Catch specific before general: Order
catchclauses from the most specific case to a final catch-all, and never leave that catch-all empty -- log or rethrow so no failure is silently absorbed. - Use try-question-mark only when nil is a real answer: Convert to an optional when "absent, and that is acceptable" is genuinely the meaning, not merely to mute an inconvenient error you would rather not handle.
- Keep throwing functions small and guard early: A function that throws for one clear reason is easy to reason about; validate inputs up front with
guardand throw immediately rather than deep inside nested logic. - Put actionable context in the error: Include which field, which id, or which line failed, so whoever catches it can respond precisely instead of receiving a bare "something went wrong".
Practice Exercises
- Typed throw and catch: Define an
enum BrewError: Errorwith caseswaterTooCold(Int)andnoBeans. Write a throwingbrewfunction and ado/catchthat binds the temperature fromwaterTooColdand prints a specific message for each case. - Three faces of a throw: Using a single throwing
parse(_:)function, showtryinside ado/catch,try?with a??fallback, and a provably safetry!, then print the three outcomes side by side. - Convert to Result: Rewrite a throwing
fetch(id:)to returnResult<String, MyError>. Build an array of several calls, iterate it with aswitch, and usemapto transform one success without touching the failures. - Prove defer runs: Write a function that opens a resource, registers cleanup with
defer, and throws partway through on some inputs. Call it with an input that succeeds and one that throws, and show the cleanup line prints in both runs.