Throw-Catch

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the Lesson01-Review-Basics playground, click Next to open the Lesson01-throw-catch page.

Bakery Model

Here’s a model for a bakery that sells pastries. The itemsForSale dictionary contains Pastry objects, each with flavor and numberOnHand properties.

Error Protocol

Swift has an Error protocol, which forms the basis of its error-handling architecture. Any type conforming to this protocol represents an error and can take part in error-handling routines.

Throwing an Error

Edit open(_:) to throw noInventory or noPower:

Catching an Error

If your code calls a function that can throw an error, you usually want to catch and handle any errors it throws. To do this, you try to call it, inside a do closure. Enclose the calls to bakery.open and bakery.orderPastry in a do closure and insert the keyword try:

Ffelj ftejak
Dxuzf wyezud

Ta jivw isat
Do balq egoq

Not Caring About an Error

If you don’t care about the error details, you don’t need do and catch closures. Add the following code to wrap the result of each throwing function in an optional.

ccv? genarhj gov.
nnf? dobutgt mig.

Knowing Errors Won’t Happen

If you know your code is never going to fail, or you want your program to terminate if the function throws an error, use try! — add the following code and run it:

lfp! xpgasg iqcih agl gtowces.
rhs! lttacw emcun ift ftujcog.

The Problem With throws

You want the compiler to help you write the best possible code. Defining a function that throws has an obvious problem: You can’t tell the compiler what specific types of error the function can throw, so it can give you only a limited amount of assistance with auto-completion and checking.

See forum comments
Download course materials from Github
Previous: Optionals Next: Conclusion