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

The Error Protocol

The Error protocol is a label you put on your own custom type to say "this represents something going wrong."

Defining a Custom Error Type

Conforming an enum to Error turns each of its cases into a distinct, throwable error value.

Example: Defining a Custom Error Type

markup
enum ValidationError: Error {
    case tooShort
    case tooLong
}
let error = ValidationError.tooShort
print(error)

Errors with Associated Values

Just like any other enum, an error type can carry associated values to provide more detail about what went wrong.

Example: Errors with Associated Values

markup
enum ValidationError: Error {
    case tooShort(minimum: Int)
    case tooLong(maximum: Int)
}
let error = ValidationError.tooShort(minimum: 5)
print(error)
Common Mistakes
  1. Forgetting an error type must conform to the empty Error protocol before it can be thrown with throw.
  2. Using a plain String or generic type as an error instead of a proper enum conforming to Error, losing type-safety and clarity about what can go wrong.
  3. Defining many unrelated error cases in a single giant enum instead of separate, focused error types per domain.
Chapter Summary
  • Any type can represent an error by conforming to the Error protocol.
  • Enums are the most common way to define a set of related error cases.
  • Error itself has no requirements -- it's a marker protocol.
  • A well-designed error type communicates exactly what can go wrong in a given operation.
🔒

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.