Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

Chapter 7. Exceptions

Our last chapter in this part of the book has to do with exceptions—events that can modify the flow of control through a program. In Python, exceptions can be both intercepted and triggered by our programs. They are processed by two new statements we’ll study in this chapter:

try

Catches exceptions raised by Python or a program

raise

Triggers an exception manually

With a few exceptions (pun intended), we’ll find that exception handling is simple in Python, because it’s integrated into the language itself as another high-level tool.

Why Use Exceptions?

In a nutshell, exceptions let us jump around arbitrarily large chunks of a program. Remember that pizza-making robot we talked about in the last chapter? Suppose we took the idea seriously and actually built such a machine (there are worse hobbies, after all). To make a pizza, our culinary automaton would need to execute a plan, which we implement as a Python program. It would take an order, prepare the dough, add toppings, bake the pie, and so on.

Now, suppose that something goes very wrong during the “bake the pie” step. Perhaps the oven is broken. Or perhaps our robot miscalculates its reach and spontaneously bursts into flames. Clearly, we want to be able to jump to code that handles such states quickly (especially if our robot is melting all over the kitchen floor!). Since we have no hope of finishing the pizza task in such unusual cases, we might as well abandon the entire plan.

That’s exactly what exceptions ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata