Skip to the workspace
Pebellslearn by building
Core Programming Concepts  ›  Lesson

Error Handling

Error Handling 12 minSwift functions that can fail are marked throws, callers mark each risky call with try, and do-catch blocks handle errors, while try? and try! convert them to optionals or crashes.

ios / Error Handling

Explore each scene at your own pace.

01 · The rule

The rule

Error Handling

Saving a hike can fail: the disk is full, the name is empty, or the file is corrupted. An app that pretends nothing can go wrong shows a blank screen or loses data. Swift makes failure part of a function's signature, so callers cannot forget it.

The rule

throws warns, try marks the risk, catch handles the fall.

Errors in Swift are values of any type that conforms to the Error protocol — usually an enum:

enum SaveError: Error {
    case emptyName
    case diskFull
}

A function that can fail is marked throws, and uses throw to fail:

func save(_ hike: Hike) throws {
    guard !hike.name.isEmpty else { throw SaveError.emptyName }
    // ... write to disk, which may also throw
}

A caller must mark each throwing call with try, and handle errors in a do–catch:

do {
    try save(hike)
    showSavedBanner()
} catch SaveError.emptyName {
    showMessage("Give your hike a name.")
} catch {
    showMessage("Could not save: \(error.localizedDescription)")
}

When the first try fails, the rest of the do block is skipped and the matching catch runs. The last plain catch catches anything else and gives you an implicit error constant.

Two shortcuts change a throwing call into something else:

  • try? turns the result into an optional: nil if it threw. Use it when failure just means "no value".
  • try! asserts it will never throw, and crashes if it does. Rarely appropriate.

A function can also rethrow by simply being throws itself and writing try without a do — the error passes up to its caller.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.