TExcelTAD
Home › Swift › Swift Error Handling

Swift Error Handling

Things go wrong: a file is missing, a password is too short, a network request times out. Swift handles recoverable failures with errors: a function throws an error, and the caller must deal with it using try and do/catch. The compiler makes sure no thrown error is silently ignored.

Defining errors

An error is any type that adopts the Error protocol. Enums are perfect for this, because each case names one kind of failure — and cases can carry details as associated values.

swift
enum PasswordError: Error {
    case tooShort(minimum: Int)
    case noDigits
    case common
}

Throwing and catching

Mark a function that can fail with throws. Inside it, throw stops the function immediately. Callers write try in front of the call, inside a do block, and handle failures in catch clauses.

swift · try it yourself
enum PasswordError: Error {
    case tooShort(minimum: Int)
    case noDigits
    case common
}

func validate(_ password: String) throws -> String {
    if password.count < 8 {
        throw PasswordError.tooShort(minimum: 8)
    }
    if !password.contains(where: { $0.isNumber }) {
        throw PasswordError.noDigits
    }
    if ["password1", "12345678"].contains(password) {
        throw PasswordError.common
    }
    return "Strong enough"
}

for candidate in ["abc", "sunshine", "password1", "blue42Sky"] {
    do {
        let verdict = try validate(candidate)
        print("\(candidate): \(verdict)")
    } catch PasswordError.tooShort(let minimum) {
        print("\(candidate): needs at least \(minimum) characters")
    } catch PasswordError.noDigits {
        print("\(candidate): add a number")
    } catch {
        print("\(candidate): rejected (\(error))")   // `error` is available automatically
    }
}
abc: needs at least 8 characters
sunshine: add a number
password1: rejected (common)
blue42Sky: Strong enough

The last catch without a pattern catches everything else, and gives you the thrown value as error.

Propagating errors

A throwing function does not have to handle errors itself — if it calls another throwing function with try and has no catch, the error travels up to its caller:

swift · try it yourself
enum BankError: Error {
    case insufficientFunds(needed: Int)
    case accountLocked
}

struct Account {
    var balance: Int
    var locked = false

    mutating func withdraw(_ amount: Int) throws {
        guard !locked else { throw BankError.accountLocked }
        guard amount <= balance else {
            throw BankError.insufficientFunds(needed: amount - balance)
        }
        balance -= amount
    }
}

func payRent(from account: inout Account) throws {
    try account.withdraw(500)        // any error simply propagates
    print("Rent paid, \(account.balance) left")
}

var mine = Account(balance: 800)
var empty = Account(balance: 120)

for i in 1...2 {
    do {
        if i == 1 { try payRent(from: &mine) } else { try payRent(from: &empty) }
    } catch BankError.insufficientFunds(let needed) {
        print("Short by \(needed)")
    } catch {
        print("Other error:", error)
    }
}
Rent paid, 300 left
Short by 380

try? and try!

Form What happens on error Result type
try Error is thrown to the enclosing do/caller The plain value
try? Error is discarded, result is nil An optional
try! The program crashes The plain value
swift · try it yourself
enum ParseError: Error { case notANumber(String) }

func parseAge(_ text: String) throws -> Int {
    guard let n = Int(text) else { throw ParseError.notANumber(text) }
    return n
}

let a = try? parseAge("34")
let b = try? parseAge("thirty")
print(a as Any, b as Any)

let age = (try? parseAge("abc")) ?? 0     // fall back to a default
print(age)
Optional(34) nil
0

Note: Use try! only when failure is truly impossible (for example, decoding JSON you wrote yourself in the same file). If it fails, the app crashes.

Cleaning up with defer

A defer block runs when the current scope ends — whether it ends normally or because an error was thrown. It is ideal for closing files or releasing resources.

swift · try it yourself
enum JobError: Error { case failed }

func runJob(shouldFail: Bool) throws {
    print("open connection")
    defer { print("close connection") }

    if shouldFail { throw JobError.failed }
    print("job done")
}

try? runJob(shouldFail: false)
print("---")
try? runJob(shouldFail: true)
open connection
job done
close connection
---
open connection
close connection

The Result type

Sometimes you want to store a success-or-failure value instead of throwing immediately — for example to pass it to a completion handler. Result<Success, Failure> is an enum with .success and .failure cases:

swift · try it yourself
enum LookupError: Error { case unknownCode }

func country(for code: String) -> Result<String, LookupError> {
    switch code {
    case "VN": return .success("Vietnam")
    case "JP": return .success("Japan")
    default:   return .failure(.unknownCode)
    }
}

for code in ["VN", "XX"] {
    switch country(for: code) {
    case .success(let name): print(code, "→", name)
    case .failure(let err):  print(code, "→ error:", err)
    }
}

// Convert a Result back into a throwing call:
let name = try? country(for: "JP").get()
print(name ?? "?")
VN → Vietnam
XX → error: unknownCode
Japan

Tip: Since Swift 6 you can declare typed throws: func load() throws(LoadError). The catch then knows the exact error type. Plain throws (any Error) is still the most common choice.

Test yourself

What does try? return when the called function throws?

  1. It crashes
  2. nil
  3. The error
  4. An empty string

When does a defer block run?

  1. Immediately
  2. Only when an error is thrown
  3. When the current scope exits, for any reason
  4. At program end

Inside a plain catch { ... } with no pattern, how do you access the thrown error?

  1. $0
  2. error
  3. self.error
  4. thrown