1.13 Error Handling
Swift handles errors in a similar way to other languages, but with a few differences. There are 4 main keywords:
throws
- this keyword is added to a function to indicate it can throw an error. E.g.
func canThrowAnError() throws {
// this function may or may not throw an error
}
do
- This creates a new scope in which multiple statements which can throw errors can be placed. These are then handled by...catch
- These blocks contain code for handling errors.try
- This keyword is placed before calling functions which can throw errors in ado
block.
The do
, catch
and try
are used as follows:
do {
try canThrowAnError()
// no error was thrown
} catch {
// an error was thrown
}
Putting it all together:
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}