A do block contains throwing work, and catch blocks handle matching errors.

Handle one known failure

accountLocked
do_catch.swift
Replay: real traced execution (multi-file project)
enum LoginError: Error {
    case locked
}

func loginStatus(_ locked: Bool) throws -> String {
    if locked {
        throw LoginError.locked
    }
    return "signed in"
}

let accountLocked = false
let status: String

do {
    status = try loginStatus(accountLocked)
} catch LoginError.locked {
    status = "ask for reset"
}

print(status)
enum LoginError: Error {
    case locked
}

func loginStatus(_ locked: Bool) throws -> String {
    if locked {
        throw LoginError.locked
    }
    return "signed in"
}

let accountLocked = true
let status: String

do {
    status = try loginStatus(accountLocked)
} catch LoginError.locked {
    status = "ask for reset"
}

print(status)
  1. accountLocked ← false

    12let accountLocked→ false = false  //@accountLocked=true13let status: String1415do {16    status = try loginStatus(accountLockedfalse)17} catch LoginError.locked {
  2. func loginStatus(_ locked: Bool) throws -> String

    5func loginStatus(_ lockedfalse: Bool) throws -> String {6    if locked {7        throw LoginError.locked8    }9    return "signed in"10}
  3. status ← signed in

    15do {16    status→ signed in = try loginStatus(accountLockedfalse)17} catch LoginError.locked {18    status = "ask for reset"19}2021print(statussigned in)
    outputsigned in
  1. accountLocked ← true

    12let accountLocked→ true = true13let status: String1415do {16    status = try loginStatus(accountLockedtrue)17} catch LoginError.locked {
  2. func loginStatus(_ locked: Bool) throws -> String

    5func loginStatus(_ lockedtrue: Bool) throws -> String {6    if locked {
  3. if locked

    5func loginStatus(_ locked: Bool) throws -> String {6    if lockedtrue {7        throw LoginError.locked8    }
  4. status ← ask for reset

    17} catch LoginError.locked {18    status→ ask for reset = "ask for reset"19}2021print(statusask for reset)
    outputask for reset
do catch `do` marks the part of the program that may throw; `catch` describes the recovery path.