Exceptions

Exceptions are events that modify a program's flow, either intentionally or due to errors. Some examples are trying to open a file that doesn't exist, or when the program reaches a marker, such as the completion of a loop. Exceptions, by definition, don't occur very often; hence, they are the exceptions to the rule and a special class has been created for them.

Exceptions are everywhere in Python. Virtually every module in the Python standard library uses them, and Python itself will raise them in a variety of different circumstances. Here are just a few examples:

  • Accessing a non-existent dictionary key will raise a KeyError exception
  • Searching a list for a non-existent value will raise a ValueError exception
  • Calling a non-existent ...

Get Learn Programming in Python with Cody Jackson now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.