Skip to content

Latest commit

 

History

History
40 lines (35 loc) · 1.41 KB

1.13 - Error Handling.md

File metadata and controls

40 lines (35 loc) · 1.41 KB

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 a do 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)
}

Previous Note | Back To Contents | Next Note