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.
Syntax
do {
try throwingCall()
} catch ErrorTypeA.caseName {
// handle A
} catch ErrorTypeB {
// handle B
} catch {
// any other error, available as `error`
}
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
// Define an enum `NetworkError` listing its possible cases
enum NetworkError: Error {
// Case `timeout`
case timeout
}
// Define an enum `ParsingError` listing its possible cases
enum ParsingError: Error {
// Case `malformed`
case malformed
}
func fetchData(shouldTimeout: Bool) throws {
// Check whether `shouldTimeout`
if shouldTimeout {
throw NetworkError.timeout
}
throw ParsingError.malformed
}
do {
try fetchData(shouldTimeout: true)
} catch is NetworkError {
// Print "A network error occurred" to the console
print("A network error occurred")
} catch is ParsingError {
// Print "A parsing error occurred" to the console
print("A parsing error occurred")
} catch {
// Print "Some other error" to the console
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
// Define an enum `AppError` listing its possible cases
enum AppError: Error {
// Case `notFound`
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)" to the console
print("App error: \(appError)")
} catch {
// Print "Unhandled error: \(error)" to the console
print("Unhandled error: \(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
- 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: