← Back to Swift Course | Chapter 11: Error Handling | Lesson 6 of 6

Handling Multiple Error Types

Sometimes different parts of a program can fail in different ways, so you need a plan for catching each specific kind of trouble.

Catching Different Error Types Separately

Multiple catch clauses can each target a distinct error type thrown by different parts of the same do block.

Example: Catching Different Error Types Separately

markup
enum NetworkError: Error {
    case timeout
}
enum ParsingError: Error {
    case malformed
}
func fetchData(shouldTimeout: Bool) throws {
    if shouldTimeout {
        throw NetworkError.timeout
    }
    throw ParsingError.malformed
}
do {
    try fetchData(shouldTimeout: true)
} catch is NetworkError {
    print("A network error occurred")
} catch is ParsingError {
    print("A parsing error occurred")
} catch {
    print("Some other error")
}

Inspecting a Generic Caught Error

A plain catch binds the thrown value as error of type Error, which can be cast to a specific type when more detail is needed.

Example: Inspecting a Generic Caught Error

markup
enum AppError: Error {
    case notFound(id: Int)
}
func lookup(id: Int) throws {
    throw AppError.notFound(id: id)
}
do {
    try lookup(id: 42)
} catch let appError as AppError {
    print("App error: \(appError)")
} catch {
    print("Unhandled error: \(error)")
}
Common Mistakes
  1. Trying to catch two completely different error enum types in the same single catch clause without pattern matching each type separately.
  2. Forgetting a generic catch (with no type) binds a plain Error value, which then requires casting to check a specific concrete error type.
  3. Not centralizing related error cases into a shared enum when a function can fail in several closely related ways, spreading complexity across many ad hoc error types.
Chapter Summary
  • Different throwing functions can define and throw their own distinct Error-conforming types.
  • A do block can have multiple catch clauses, each matching a specific error type or case.
  • A generic catch binds the error as the general Error type, which may need casting to inspect further.
  • Grouping related failure cases into one enum keeps error handling for a subsystem organized.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.