< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204175206119224211141058020

Chapter 10. Errors And Exceptions

Chapter Topics

  • What Are Exceptions?

  • Exceptions in Python

  • Detecting and Handling Exceptions

    • try-except Statement

    • Exception Arguments

    • else Statement

    • try-finally Statement

  • Exceptions Are Classes

  • Raising Exceptions

    • raise Statement

  • Assertions

    • assert Statement

  • Standard Exceptions

  • Creating Exceptions

  • Why Exceptions (Now)?

  • Why Exceptions at All?

  • Related Modules

Errors are an everyday occurrence in the life of a programmer. In days hopefully long since past, errors were either fatal to the program (or perhaps the machine) or produced garbage output that was neither recognized as valid input by other computers or programs nor by the humans who submitted the job to be run. Any time an error occurred, execution was halted until the error was corrected and code was re-executed. Over time, demand surged for a "softer" way of dealing with errors other than termination. Programs evolved such that not every error was malignant, and when they did happen, more diagnostic information was provided by either the compiler or the program during run-time to aid the programmer in solving the problem as quickly as possible. However, errors are errors, and any resolution usually took place after the program or compilation process was halted. There was never really anything a piece of code could do but exit and perhaps leave some crumbs hinting at a possible cause—until exceptions and exception handling came along.

Although we have yet to cover classes and object-oriented programming in Python, many of the concepts presented here involve classes and class instances.[1] We conclude the chapter with an optional section on how to create your own exception classes. Older versions of Python utilized string exceptions, which are not common any more. We recommend using only class-based exceptions for all future development.

[1] As of Python 1.5, all standard exceptions are implemented as classes. If new to classes, instances, and other object-oriented terminology, the reader should check Chapter 13 for clarification.

This chapter begins by exposing the reader to exceptions, exception handling, and how they are supported in Python. We also describe how programmers can generate exceptions within their code. Finally, we reveal how programmers can create their own exception classes.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.