14 Exceptions

 

This chapter covers

  • Understanding exceptions
  • Handling exceptions in Python
  • Using the with keyword

This chapter discusses exceptions, which are language features specifically aimed at handling unusual circumstances during the execution of a program. The most common use for exceptions is to handle errors that arise during the execution of a program, but they can also be used effectively for many other purposes. Python provides a comprehensive set of exceptions, and new ones can be defined by users for their own purposes.

The concept of exceptions as an error-handling mechanism has been around for some time. C and Perl, the most commonly used systems and scripting languages, don’t provide any exception capabilities, and even programmers who use languages such as C++, which does include exceptions, are often unfamiliar with them. This chapter doesn’t assume familiarity with exceptions on your part but instead provides detailed explanations.

14.1 Introduction to exceptions

The following sections provide an introduction to exceptions and how they’re used. If you’re already familiar with exceptions, you can skip directly to section 14.2.

14.1.1 General philosophy of errors and exception handling

14.1.2 A more formal definition of exceptions

14.1.3 Handling different types of exceptions

14.2 Exceptions in Python

14.2.1 Types of Python exceptions

14.2.2 Raising exceptions

14.2.3 Catching and handling exceptions

14.2.4 Defining new exceptions

14.2.5 Exception groups

14.2.6 Debugging programs with the assert statement

14.2.7 The exception inheritance hierarchy

14.2.8 Example: A disk-writing program in Python

14.2.9 Example: Exceptions in normal evaluation

14.2.10 Where to use exceptions

14.3 Context managers using the with keyword

14.4 Adding exceptions

14.4.1 Solving the problem with AI-generated code

14.4.2 Solutions and discussion

Summary