Skip to Content
Learning Python, 6th Edition
book

Learning Python, 6th Edition

by Mark Lutz
February 2025
Intermediate to advanced
1172 pages
42h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Python, 6th Edition

Chapter 35. Exception Objects

So far, this book has been somewhat vague about what an exception actually is. This chapter clears up the mystery by disclosing the facts behind exception objects—both built-in and user-defined. As suggested in the preceding chapters, exceptions are identified by class instance objects. This is what is raised and propagated along by exception processing, and the source of the class matched against except clauses in try statements.

Although this means you must use object-oriented programming to define new exceptions in your programs—and introduces a knowledge dependency lamented in the prior chapter’s note—basing exceptions on classes and OOP offers a number of benefits. Among them, class-based exceptions support:

Flexible exception categories

Exception classes allow code to choose specificity and ease future changes. Adding new exception subclasses, for example, need not require changes in try statements.

State information and behavior

Exception classes provide a natural place to store context for use in the try handler. Both attributes and methods, for example, are available on the raised instance.

Reuse by inheritance

Exceptions classes can participate in inheritance hierarchies to obtain and customize common behavior. Inherited error displays, for example, can provide a common look and feel.

Because of these advantages, class-based exceptions support program evolution and larger systems well. As you’ll learn here, all built-in exceptions are identified ...

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

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098171292Errata PageSupplemental Content