Handling errors
After your program throws an error, you need to handle that error. There are two ways to approach this problem: You can handle your errors immediately, or you can bubble them up to another level.
To choose your approach, you need to think about where it makes the most sense to handle the error. If it makes sense to handle the error immediately, then do so. If you’re in a situation where you have to alert the user and have her take action, but you’re several function calls away from a user interface element, then it makes sense to bubble up the error until you reach the point where you can alert the user.
It’s entirely up to you when to handle the error, but not handling it isn’t an option. Swift requires you to handle your error at some point in the chain, or your program won’t compile.
Replace the previous line of code with this:
do {
try bakery.orderPastry(item: "Albatross",
amountRequested: 1,
flavor: "AlbatrossFlavor")
} catch BakeryError.doNotSell { print("Sorry, but we don't sell albatross")
} catch BakeryError.wrongFlavor {
print("Sorry, but we don't carry albatross flavor")
} catch BakeryError.tooFew {
print("Sorry, we don't have enough albatross to fulfill your order")
}
Code that can throw errors must always be inside a do block which creates a new scope. Even more, the exact points where errors can be thrown must be marked with try. The try above doesn’t actually do anything. It serves as a reminder so that whoever reads your code can easily understand what can go wrong.
You’re now catching each error condition and providing useful feedback to the user about why you can’t fulfill their order.