Swift offers first class support for catching, propagating, and manipulating recoverable errors at runtime. By recoverable, we mean errors that can be foreseen and handled suitably.
What Swift's Error
handling approach offers us is a dedicated branching mechanism and a syntax to support it. It's a kind of specialized if-else
mechanism, but one that, crucially, forces a calling function to deal with an error that may occur, by declaring itself as a throwing function, using the throws
keyword.
Error handling thus becomes a graceful and uncomplicated way of dealing with functions that can fail.
Sounds a bit esoteric, I admit, but no worries, there is no magic involved. We'll get to the details shortly, but there are basically four ways to handle Swift errors:
- Assert that the error will not occur
- Handle the error as an optional value
- Handle the error using a
do-catch
statement - Propagate the error to the calling function
Exactly how all that works...