Login
📚 Introduction to Python Programming
Chapters ▾
⇩ 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.