Thuta Learning
Swift
AdvancedProgrammingBeginner

Error Handling

SwiftLesson 2525 min

What you'll walk away with

  • Explain the type, ownership, and runtime behavior of Error Handling
  • Test nil, error, boundary, and concurrency cases
  • Write safe and testable Swift

Explain it simply

Error Handling, in plain language

Any app can run into runtime issues — a missing file, a failed network request, a failed payment, bad input. Swift lets you handle errors properly with throw , throws , do-catch , try .

Problem → Why → Solution

The problem — why this concept matters

Calling a function that needs try without wrapping it in do-catch can cause a compile error.

A common mistake

Assuming one sample output proves nil, ownership, actor isolation, and every error path.

Core concept — understand how it works

For Error Handling, define the input domain, exhaustive paths, return values, side effects, and failure or cancellation behavior. Prefer guard statements, typed errors, and explicit propagation over force unwraps or silent suppression.

Mental model
  1. optional or fallible input
  2. pattern and error handling
  3. safe value or recovery

Explain the type, ownership, and runtime behavior of Error Handling

Core syntax or pattern

swift
enum LoginError: Error {
    case emptyUsername
    case wrongPassword
}

func login(username: String, password: String) throws {
    if username.isEmpty {
        throw LoginError.emptyUsername
    }

    if password != "123456" {
        throw LoginError.wrongPassword
    }

    print("Login success")
}

do {
    try login(username: "sai", password: "wrong")
} catch LoginError.emptyUsername {
    print("Username is required")
} catch LoginError.wrongPassword {
    print("Password is incorrect")
} catch {
    print("Something went wrong")
}

For Error Handling, define the input domain, exhaustive paths, return values, side effects, and failure or cancellation behavior. Prefer guard statements, typed errors, and explicit propagation over force unwraps or silent suppression.

Read the code step by step

  1. optional or fallible inputenum LoginError: Error {

    Any app can run into runtime issues — a missing file, a failed network request, a failed payment, bad input. Swift lets you handle errors properly with throw , throws , do-catch , try .

  2. pattern and error handlingprint("Login success")

    For Error Handling, define the input domain, exhaustive paths, return values, side effects, and failure or cancellation behavior. Prefer guard statements, typed errors, and explicit propagation over force unwraps or silent suppression.

  3. safe value or recovery}

    Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Execution flow
  1. optional or fallible input
  2. pattern and error handling
  3. safe value or recovery

Success

Explain the type, ownership, and runtime behavior of Error Handling

Failure

Calling a function that needs try without wrapping it in do-catch can cause a compile error.

Any app can run into runtime issues — a missing file, a failed network request, a failed payment, bad input. Swift lets you handle errors properly with throw, throws, do-catch, try.

swift
enum LoginError: Error {
    case emptyUsername
    case wrongPassword
}

func login(username: String, password: String) throws {
    if username.isEmpty {
        throw LoginError.emptyUsername
    }

    if password != "123456" {
        throw LoginError.wrongPassword
    }

    print("Login success")
}

do {
    try login(username: "sai", password: "wrong")
} catch LoginError.emptyUsername {
    print("Username is required")
} catch LoginError.wrongPassword {
    print("Password is incorrect")
} catch {
    print("Something went wrong")
}

login function is marked throws since it can fail. Calling it requires try, and if it fails you land in one of the catch blocks.

You should see
Password is incorrect

Real-world usage

How to apply it in a real project

Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Mini challenge

Build it yourself

Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
swift
enum LoginError: Error {
    case emptyUsername
    case wrongPassword
}

func login(username: String, password: String) throws {
    if username.isEmpty {
        throw LoginError.emptyUsername
    }

    if password != "123456" {
        throw LoginError.wrongPassword
    }

    print("Login success")
}

do {
    try login(username: "sai", password: "wrong")
} catch LoginError.emptyUsername {
    print("Username is required")
} catch LoginError.wrongPassword {
    print("Password is incorrect")
} catch {
    print("Something went wrong")
}

Expected: Explain the type, ownership, and runtime behavior of Error Handling

Show hint

Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Quick quiz 1 / 3

What best describes the core idea of Error Handling?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • optional or fallible input → pattern and error handling → safe value or recovery
  • For Error Handling, define the input domain, exhaustive paths, return values, side effects, and failure or cancellation behavior. Prefer guard statements, typed errors, and explicit propagation over force unwraps or silent suppression.
  • Calling a function that needs try without wrapping it in do-catch can cause a compile error.
  • Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

The Swift Programming Language — Swift.org

Easy traps

  • Calling a function that needs try without wrapping it in do-catch can cause a compile error.
  • Assuming one sample output proves nil, ownership, actor isolation, and every error path.
  • Bypassing compiler safety with force unwraps or unchecked shared mutable state.

Hands-on Exercise

Run and test an original Error Handling example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

You'll know it worked when: Password is incorrect

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Error Handling | Thuta Learning