Error handling
Optionals, thrown errors, Result, and preconditions: choosing how a function reports failure, catching errors by pattern, typed throws, defer, and a working method for debugging.
- CS61A
- Debugging
- Swift book
- Error Handling
The calculator in Lesson 20 could be handed (/ 1 0) or (+ 1, and it had
to do something sensible. Every real program meets input it cannot handle,
files that are missing, and networks that are down. This lesson is about
what a function should do when it cannot do its job, and about finding out
why your own program did not do what you meant.
Four ways to fail
Swift gives you four tools, for four different situations:
| Situation | Tool | Example |
|---|---|---|
| There may be no answer, and the reason is obvious | return an optional | Int("abc") is nil |
| The operation can fail in ways the caller should handle | throw an error | reading a file, parsing a program |
| A failure must be stored or passed along as a value | return a Result |
collecting outcomes of many tasks |
| The program itself is wrong | stop with a precondition | an array index out of range |
The first three are for failures the program expects: bad input, a missing file. The last is for failures that mean there is a bug. Stopping immediately, with a message pointing at the broken assumption, is better than carrying on with a wrong value and failing somewhere far away.
Throwing errors
An error is a value of any type that conforms to the Error protocol. An
enum is the natural choice, since the ways an operation can fail are usually
a fixed list, and associated values can carry the details:
enum WithdrawalError: Error {
case invalidAmount
case insufficientFunds(shortBy: Int)
case frozen
}
struct Account {
var balance: Int
var isFrozen = false
mutating func withdraw(_ amount: Int) throws -> Int {
guard amount > 0 else {
throw WithdrawalError.invalidAmount
}
guard !isFrozen else {
throw WithdrawalError.frozen
}
guard amount <= balance else {
throw WithdrawalError.insufficientFunds(shortBy: amount - balance)
}
balance -= amount
return amount
}
}
throws in the signature says the function can fail. throw ends the
function, like return, but hands back an error instead of a value. Note
where the checks are: before balance changes. A function that throws
halfway through a change leaves things half-changed, so check first, then
act.
Catching
Calling a throwing function requires try, which marks every place where
control might jump away. To handle the error, put the call inside do and
add catch clauses. Each catch is a pattern, as in Lesson 19:
enum WithdrawalError: Error {
case invalidAmount
case insufficientFunds(shortBy: Int)
case frozen
}
struct Account {
var balance: Int
var isFrozen = false
mutating func withdraw(_ amount: Int) throws -> Int {
guard amount > 0 else { throw WithdrawalError.invalidAmount }
guard !isFrozen else { throw WithdrawalError.frozen }
guard amount <= balance else { throw WithdrawalError.insufficientFunds(shortBy: amount - balance) }
balance -= amount
return amount
}
}
var account = Account(balance: 50)
for amount in [20, 40, -5] {
do {
let cash = try account.withdraw(amount)
print("withdrew", cash)
} catch WithdrawalError.insufficientFunds(let shortBy) {
print("short by", shortBy)
} catch {
print("failed:", error)
}
}
print(account.balance)
// withdrew 20
// short by 10
// failed: invalidAmount
// 30
The second catch has no pattern, so it catches everything, and names the
error error automatically. When withdraw throws, the rest of the do
block is skipped: print("withdrew", …) never runs for 40 or −5.
Letting errors travel
A function does not have to handle errors from the functions it calls. If
it is marked throws itself, it can just write try and let any error
continue up to its caller:
enum WithdrawalError: Error {
case insufficientFunds(shortBy: Int)
}
func withdraw(_ amount: Int, from balance: inout Int) throws {
guard amount <= balance else {
throw WithdrawalError.insufficientFunds(shortBy: amount - balance)
}
balance -= amount
}
func payRent(from balance: inout Int) throws {
try withdraw(1200, from: &balance)
print("rent paid")
}
var balance = 1000
do {
try payRent(from: &balance)
} catch {
print("could not pay rent:", error)
}
// could not pay rent: insufficientFunds(shortBy: 200)
This is how the calculator worked: apply threw, evaluate passed the error
along with try, and only run caught it. Errors are handled where
something sensible can be done about them, which is often far from where
they happen. And every try along the way is a visible reminder that the
code there might not continue.
try? and try!
Two shortcuts convert an error into something else:
try?turns an error intonil. The result is an optional, so this is how you go from “throws” back to “might be missing”, when the reason does not matter.try!promises that no error will happen, and crashes if one does. Use it only when an error would mean a bug, such as parsing a constant you wrote yourself.
What would Swift print?
enum ParseError: Error {
case notANumber
}
func parse(_ text: String) throws -> Int {
guard let n = Int(text) else {
throw ParseError.notANumber
}
return n
}
let numbers = ["4", "x", "10"].compactMap { try? parse($0) }
print(numbers, try! parse("7"))Show answer and explanation
Answer[4, 10] 7
try? turns the failure for "x" into nil, and compactMap drops it.
try! parse("7") is safe because "7" is a number; try! parse("x") would
crash.
Typed throws
A plain throws function can throw any error at all, which is why the
catch-all catch is usually needed. Since Swift 6, a function can instead
declare exactly which type it throws:
enum ParseError: Error {
case empty
case notANumber(String)
case negative(Int)
}
func parseCount(_ text: String) throws(ParseError) -> Int {
guard !text.isEmpty else {
throw .empty
}
guard let n = Int(text) else {
throw .notANumber(text)
}
guard n >= 0 else {
throw .negative(n)
}
return n
}
for text in ["12", "", "twelve", "-3"] {
do {
print(try parseCount(text))
} catch {
switch error {
case .empty: print("nothing typed")
case .notANumber(let t): print("\(t) is not a number")
case .negative(let n): print("\(n) is below zero")
}
}
}
// 12
// nothing typed
// twelve is not a number
// -3 is below zero
Because parseCount can only throw a ParseError, the compiler knows the
type of error in the catch block, and the switch on it must be
exhaustive, with no default needed. throw .empty can leave out the type
name for the same reason.
Cleaning up with defer
Code after a throw or an early return never runs. When something must
happen however a function exits, such as closing a file, releasing a lock, or
restoring a setting, put it in a defer block. It runs when the enclosing
scope ends, whichever way it ends:
var openFiles = 0
func processFile(failing: Bool) throws -> String {
openFiles += 1
defer {
openFiles -= 1
}
if failing {
throw ParseProblem.badLine
}
return "done"
}
enum ParseProblem: Error {
case badLine
}
print(try processFile(failing: false), openFiles) // done 0
print((try? processFile(failing: true)) == nil, openFiles) // true 0
The counter goes back to 0 both times. Writing the cleanup right next to the
setup, instead of before every return and throw, means a new early exit
added later cannot forget it.
What would Swift print?
func steps() -> String {
var log = "start "
defer { print("first defer") }
defer { print("second defer") }
log += "end"
return log
}
print(steps())Show answer and explanation
Answersecond defer\nfirst defer\nstart end
Deferred blocks run in reverse order, last one first, just before the function
returns. The print of the returned value happens after the function has
finished, so it comes last.
Result: failure as a value
try works along a chain of calls. Sometimes the outcome has to be stored
instead: a batch job that processes a thousand records should report every
failure at the end, not stop at the first. Result<Success, Failure> is an
enum with two cases, .success(value) and .failure(error), so an outcome
can go in an array like any other value:
enum ParseError: Error {
case notANumber(String)
}
func parse(_ text: String) throws(ParseError) -> Int {
guard let n = Int(text) else {
throw .notANumber(text)
}
return n
}
let lines = ["10", "20", "thirty", "40", "fifty"]
let results = lines.map { line in
Result { () throws(ParseError) -> Int in try parse(line) }
}
var total = 0
var problems: [String] = []
for result in results {
switch result {
case .success(let n):
total += n
case .failure(.notANumber(let text)):
problems.append(text)
}
}
print(total, problems) // 70 ["thirty", "fifty"]
Result { … } runs the closure and captures whichever way it ended. Going
back, try result.get() returns the value or throws the error.
The closure’s type is written out, () throws(ParseError) -> Int, because
Swift does not infer typed throws for a closure: written as just
Result { try parse(line) }, the result would be Result<Int, any Error>,
and the switch could not match .notANumber inside .failure. With the
type spelled out, the results are Result<Int, ParseError>.
Result also has map, which transforms a success and passes a failure
through untouched, the same idea as map on an optional.
Errors that mean bugs
Some failures should never happen if the program is correct. Swift has three ways to check for them:
assert(condition, message)checks while you develop, and is removed from optimized builds. The labs use it for tests.precondition(condition, message)is checked in optimized builds too. Use it for requirements a caller must meet, like “the index is in range”.fatalError(message)always stops the program. Use it for code that must be unreachable.
func average(_ values: [Int]) -> Int {
precondition(!values.isEmpty, "average of no values")
return values.reduce(0, +) / values.count
}
print(average([2, 4])) // 3
print(average([])) // stops: "Precondition failed: average of no values"
Should average([]) have thrown instead? It depends on who is responsible.
If empty input is a normal thing callers will pass, and they can do
something about it, throw (or return an optional). If the documentation
says “never call this with no values”, calling it that way is a bug, and a
precondition finds the bug as early as possible. The standard library makes
the same choice: [1, 2][5] crashes rather than throwing, because an index
out of range is the caller’s mistake.
Debugging
CS61A’s debugging lecture makes a point worth repeating: bugs are normal, and finding them is a skill with a method, not luck.
Read the whole message. A compile error names the file, the line, the column, and what the compiler expected. Read the first error first: later errors are often confusion caused by the first one. A crash prints the kind of failure (“Index out of range”, “Unexpectedly found nil”) and the line where it happened, followed by the chain of calls that led there, most recent first.
Make the failure small. Find the shortest input that still fails. A bug
that appears for [3, 1, 2] but not [1, 2, 3] is already half explained.
Print what you believe. Put print calls where you think you know the
values, and check. dump(value) prints a value’s whole structure, nested
parts included, and #function and #line say where a message came from:
struct Point {
var x: Int
var y: Int
}
func move(_ p: Point) -> Point {
let result = Point(x: p.x + 1, y: p.y)
print("DEBUG", #function, result.x) // DEBUG move(_:) 2
return result
}
_ = move(Point(x: 1, y: 5))
Turn beliefs into assertions. When you discover what should be true at
some point, write an assert there. If it is ever violated again, the
program will say so right where it happens, instead of producing a wrong
answer later.
Explain it out loud. Describing, line by line, what the code does to someone else (or to a rubber duck) forces you to check what you have been assuming. Many bugs are found halfway through the explanation.
Put the lines in order
Put the lines in order so the program prints 2.
}enum Problem: Error {guard n > 0 else {let good = [3, -1, 5, 0].filter { (try? check($0)) != nil }}print(good.count)func check(_ n: Int) throws -> Int {return n}case badthrow Problem.bad
Show the correct program
enum Problem: Error {
case bad
}
func check(_ n: Int) throws -> Int {
guard n > 0 else {
throw Problem.bad
}
return n
}
let good = [3, -1, 5, 0].filter { (try? check($0)) != nil }
print(good.count)Lab 20: Error handling
Q0: What would Swift print?
What would Swift print?
enum Oops: Error {
case first, second
}
func risky(_ n: Int) throws -> Int {
if n == 1 { throw Oops.first }
if n == 2 { throw Oops.second }
return n
}
for n in [1, 2, 3] {
do {
print(try risky(n))
} catch Oops.first {
print("caught first")
} catch {
print("caught", error)
}
}Show answer and explanation
Answercaught first\ncaught second\n3
catch Oops.first matches only the first error. The second falls through to
the catch-all, whose automatic error constant prints as second.
What would Swift print?
var log: [String] = []
func work(_ fail: Bool) throws {
log.append("begin")
defer { log.append("end") }
if fail {
throw CancellationError()
}
log.append("middle")
}
try? work(true)
try? work(false)
print(log)Show answer and explanation
Answer["begin", "end", "begin", "middle", "end"]
When work(true) throws, "middle" is skipped but the deferred "end"
still runs. CancellationError is a standard error type, used here only
because it needs no definition.
Q1: Parsing an age
Write parseAge(_:), using typed throws. It returns the age for text like
"42", and throws .notANumber for text that is not a whole number,
.negative for an age below 0, and .unrealistic(age) for an age above 150.
Then write describe(_:), which returns "age 42" or a message for each
error, using an exhaustive switch on the error.
Show solution
enum AgeError: Error {
case notANumber
case negative
case unrealistic(Int)
}
func parseAge(_ text: String) throws(AgeError) -> Int {
guard let age = Int(text) else {
throw .notANumber
}
guard age >= 0 else {
throw .negative
}
guard age <= 150 else {
throw .unrealistic(age)
}
return age
}
func describe(_ text: String) -> String {
do {
return "age \(try parseAge(text))"
} catch {
switch error {
case .notANumber: return "not a number"
case .negative: return "ages cannot be negative"
case .unrealistic(let age): return "\(age) is not a realistic age"
}
}
}
assert(describe("42") == "age 42")
assert(describe("forty") == "not a number")
assert(describe("-1") == "ages cannot be negative")
assert(describe("200") == "200 is not a realistic age")Q2: A safe transfer
Write transfer(_:from:to:) for two accounts, moving money only if the whole
transfer can succeed. It throws .invalidAmount for amounts of 0 or less,
and .insufficientFunds if from does not have enough. If it throws,
neither balance may change.
struct Account {
var owner: String
var balance: Int
}
enum TransferError: Error {
case invalidAmount
case insufficientFunds
}
Show solution
struct Account {
var owner: String
var balance: Int
}
enum TransferError: Error {
case invalidAmount
case insufficientFunds
}
func transfer(_ amount: Int, from source: inout Account, to destination: inout Account) throws(TransferError) {
guard amount > 0 else {
throw .invalidAmount
}
guard source.balance >= amount else {
throw .insufficientFunds
}
source.balance -= amount
destination.balance += amount
}
var ada = Account(owner: "Ada", balance: 100)
var alan = Account(owner: "Alan", balance: 20)
try transfer(30, from: &ada, to: &alan)
assert(ada.balance == 70 && alan.balance == 50)
do {
try transfer(500, from: &ada, to: &alan)
} catch {
assert(error == .insufficientFunds)
}
assert(ada.balance == 70 && alan.balance == 50) // unchanged
assert((try? transfer(0, from: &ada, to: &alan)) == nil)Every check happens before either balance changes. error == .insufficientFunds
works because an enum without associated values is automatically
Equatable, and typed throws tell Swift what type error is.
Q3: Try, try again
Some failures are temporary. Write retry(_:_:), which calls body up to
attempts times, returning the first successful result. If every attempt
fails, it throws the last error.
Show solution
func retry<T>(_ attempts: Int, _ body: () throws -> T) throws -> T {
precondition(attempts > 0, "retry needs at least one attempt")
var lastError: Error?
for _ in 0..<attempts {
do {
return try body()
} catch {
lastError = error
}
}
throw lastError!
}
enum NetworkError: Error {
case timeout
}
var calls = 0
func flaky() throws -> String {
calls += 1
if calls < 3 {
throw NetworkError.timeout
}
return "connected"
}
assert(try! retry(5, flaky) == "connected" && calls == 3)
calls = 0
assert((try? retry(2, flaky)) == nil && calls == 2)attempts of 0 or less would be a caller’s mistake, so it is a
precondition, not an error. The force unwrap lastError! is safe because
the loop ran at least once and every iteration either returned or set it.
Q4: A report of every problem
Write summarize(_:), which parses each line as an integer and returns the
sum of the valid ones together with the line numbers (counting from 1) of
the invalid ones. Collect a Result for each line first, then build the
summary from the results.
Show solution
struct NotANumber: Error {
let text: String
}
func parse(_ text: String) throws(NotANumber) -> Int {
guard let n = Int(text) else {
throw NotANumber(text: text)
}
return n
}
func summarize(_ lines: [String]) -> (sum: Int, badLines: [Int]) {
let results = lines.map { line in Result { try parse(line) } }
var sum = 0
var badLines: [Int] = []
for (index, result) in results.enumerated() {
switch result {
case .success(let n): sum += n
case .failure: badLines.append(index + 1)
}
}
return (sum, badLines)
}
let report = summarize(["5", "x", "10", "", "-2"])
assert(report.sum == 13)
assert(report.badLines == [2, 4])Q5: Find the bugs
This function should return the average of the middle values of an array,
leaving out the smallest and the largest. It has two bugs: one gives wrong
answers, and one crashes. Find them by testing small inputs, then fix them,
throwing .tooFewValues when fewer than three values are given.
func trimmedMean(_ values: [Int]) -> Int {
let sorted = values.sorted()
let middle = sorted[1..<sorted.count]
return middle.reduce(0, +) / middle.count
}
Show solution
enum StatsError: Error {
case tooFewValues
}
func trimmedMean(_ values: [Int]) throws(StatsError) -> Int {
guard values.count >= 3 else {
throw .tooFewValues
}
let sorted = values.sorted()
let middle = sorted[1..<(sorted.count - 1)]
return middle.reduce(0, +) / middle.count
}
assert(try! trimmedMean([1, 5, 9, 100]) == 7) // (5 + 9) / 2
assert(try! trimmedMean([3, 2, 1]) == 2)
assert((try? trimmedMean([4, 4])) == nil)The first bug: sorted[1..<sorted.count] drops only the smallest value, so
[1, 5, 9, 100] gave 38 instead of 7. The second: with two values, the
middle is empty and the division is by zero; with none, sorted[1..<0] is
not even a valid range. Testing [1, 5, 9, 100] finds the first, and the
empty and two-element arrays find the second: small, deliberate inputs are
the fastest debugger.
Q6 (optional): Every problem at once
A sign-up form should report all its problems, not stop at the first.
Write validate(name:age:email:), which checks that the name is not empty,
the age is from 13 to 150, and the email contains exactly one @ with text
on both sides. It returns a User, or throws one ValidationError listing
every field that failed, in the order name, age, email.
Show solution
enum Field: Equatable {
case name, age, email
}
struct ValidationError: Error {
let fields: [Field]
}
struct User {
let name: String
let age: Int
let email: String
}
func validate(name: String, age: Int, email: String) throws(ValidationError) -> User {
var bad: [Field] = []
if name.isEmpty {
bad.append(.name)
}
if !(13...150).contains(age) {
bad.append(.age)
}
let parts = email.split(separator: "@", omittingEmptySubsequences: false)
if parts.count != 2 || parts.contains(where: \.isEmpty) {
bad.append(.email)
}
guard bad.isEmpty else {
throw ValidationError(fields: bad)
}
return User(name: name, age: age, email: email)
}
assert((try? validate(name: "Ada", age: 36, email: "ada@example.com"))?.name == "Ada")
do {
_ = try validate(name: "", age: 9, email: "ada@@example.com")
assert(false, "should have thrown")
} catch {
assert(error.fields == [.name, .age, .email])
}
do {
_ = try validate(name: "Alan", age: 41, email: "@example.com")
} catch {
assert(error.fields == [.email])
}Instead of throwing at each check, the checks append to a list, and one
error carries the list. omittingEmptySubsequences: false keeps the empty
pieces, so "@example.com" splits into "" and "example.com" and is
caught by the empty-part test. The assert(false, …) after a call that
should throw is a common testing trick, and Lesson 23 has a better one.
What’s next
Everything so far has run one step at a time. Next lesson: concurrency, and how a program can wait for slow things, like the network, without stopping everything else.