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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
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)")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to
catchtwo completely different error enum types in the same singlecatchclause without pattern matching each type separately. - Forgetting a generic
catch(with no type) binds a plainErrorvalue, which then requires casting to check a specific concrete error type. - 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
doblock can have multiplecatchclauses, each matching a specific error type or case. - A generic
catchbinds the error as the generalErrortype, 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: