Swift Academy · Lesson

do/catch & defining errors (enums)

Define error enums, throw them from functions, and handle failures with do/catch patterns (specific cases, catch let, generic catch).

Lesson 2 of 38 steps

do/catch & defining errors (enums) is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 3 lessons in total.

Overview

This lesson focuses on defining typed errors and handling them with do/catch. You'll throw an enum and catch specific cases for clear recovery paths.

Error enum

Define a custom enum that conforms to Error. Associated values add helpful context.

enum FileError: Error {
    case notFound(path: String)
    case unreadable(path: String)
    case corrupted
}
print("Defined FileError enum")

Throwing basics

Mark functions that can fail with throws. Throw specific cases when preconditions are not met.

func loadText(from path: String) throws -> String {
    if path.isEmpty { throw FileError.notFound(path: "(empty)") }
    if !path.hasSuffix(".txt") { throw FileError.unreadable(path: path) }
    return "Contents of " + path
}
print("Ready to throw on bad input")

Specific catches

Use do/try/catch. Place specific catch cases first, then a general catch for the rest.

do {
    let text = try loadText(from: "notes.txt")
    print(text)
} catch FileError.notFound(let p) {
    print("Missing file at:", p)
} catch FileError.unreadable(let p) {
    print("Cannot read:", p)
} catch {
    print("Other error:", error)
}

catch let & switch

Use catch let error as YourError and then switch to format user-friendly messages.

do {
    _ = try loadText(from: "")
} catch let error as FileError {
    switch error {
    case .notFound(let p): print("not found:", p)
    case .unreadable(let p): print("unreadable:", p)
    case .corrupted: print("file corrupted")
    }
} catch {
    print("unexpected:", error.localizedDescription)
}

Recover vs rethrow

Decide to recover (return a fallback) or rethrow to the caller. Keep rules simple and predictable.

func mustLoad(_ path: String) throws -> String {
    do {
        return try loadText(from: path)
    } catch FileError.notFound {
        // simple recovery: default content
        return "New file template"
    } catch {
        // escalate unknown issues
        throw error
    }
}
print(try? mustLoad("report.txt") ?? "(nil)")

Custom errors pattern

Quick check: What is the idiomatic way to define custom errors?

Recap

Recap: Define typed errors with an Error-conforming enum, throw precise cases, and handle them via do/catch with specific branches first, generic last.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “do/catch & defining errors (enums)” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “do/catch & defining errors (enums)”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 3 lessons in total.

What will I learn in “do/catch & defining errors (enums)”?

Define error enums, throw them from functions, and handle failures with do/catch patterns (specific cases, catch let, generic catch). You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 3.

How long does the “do/catch & defining errors (enums)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Optional chaining & error handling basics
  2. do/catch & defining errors (enums)
  3. Result types — Result
← Back to Swift Academy