Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

14.4 Handling exceptions

Learning objectives

By the end of this section you should be able to

  • Describe two exceptions that may occur when reading files.
  • Write try/except statements that handle built-in exceptions.

Runtime errors

Various errors may occur when reading a file:

  • FileNotFoundError: The filename or path is invalid.
  • IndexError/ValueError: The file's format is invalid.
  • Other errors caused by invalid contents of a file.

When an error occurs, the program terminates with an error message.

Try and except

Programs can be designed to handle exceptions, rather than terminate. A try statement runs code that might raise an exception. An except clause runs code in response to the exception.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.