The Error Protocol
The Error protocol is a label you put on your own custom type to say "this represents something going wrong."
In this page:
Syntax
enum ErrorName: Error {
case simpleCase
case caseWithData(label: Type)
}
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
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
// Case `tooShort`
case tooShort
// Case `tooLong`
case tooLong
}
// Declare a constant `error`, set to `ValidationError.tooShort`
let error = ValidationError.tooShort
// Print `error` to the console
print(error)
Login to try C/C++/Java/PHP code in the editor
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
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
// Case `tooShort`
case tooShort(minimum: Int)
// Case `tooLong`
case tooLong(maximum: Int)
}
// Declare a constant `error`, set to `ValidationError.tooShort(minimum: 5)`
let error = ValidationError.tooShort(minimum: 5)
// Print `error` to the console
print(error)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting an error type must conform to the empty
Errorprotocol before it can be thrown withthrow. - Using a plain
Stringor generic type as an error instead of a proper enum conforming toError, losing type-safety and clarity about what can go wrong. - 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
Errorprotocol. - Enums are the most common way to define a set of related error cases.
Erroritself 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: