Marquette University, view of Wisconsin Avenue  

Module 24

Exceptions

Python's philosophy is to handle the common case(s) well and then deal with exceptions. In this lesson, we look at the preferred way to handle exceptions.

A program that crashes or does not perform correctly can be life-threatening or just embarrassing. "Defensive programming" is a software development strategy that carefully checks all assumptions that are being made. For example, when implementing a function, we might want to check all assumptions on the argument of the function. This is typical "defensive" style as is practiced by experienced C-programmers.

C++ did not invent exceptions -- a way to intercept bad situation -- but made it easy to use them to deal with surprising conditions such as not being able to write a file for writing because the file system is full. Similarly to C++, Java also uses exceptions to deal with bad, surprising conditions. The Python use of exceptions is very different. Python uses exceptions to handle normal situations.

The Python philosophy is to just do it, and then ask for forgiveness later. After all this preliminaries, now let us see how exceptions work.

Syntax

Python knows of many different error conditions, such as IndexError if we access a non-existing element in a sequence type, a ModuleNotFoundError when we try to import a non-existing module, a KeyError when a key in a dictionary cannot be found, a TypeError if an operation cannot be found (as in '2'+2), and a ZeroDivisionError when we try to divide by zero. A more complete list can be found in the Python manual. Any statement or block where the programmer assumes that an error can be generated can be embedded in a "try" block. An additional "except" block then "handles" the exception with the code provided there. For example:

try:
         x=x/y   #could cause an arithmetic exception
except ZeroDivisionError:
    	 x=inf  #set x to infinity 

If in this code, y is not zero, then the execution of the statement in the try block is normal. However, if y is zero, then the execution of the statement in the try block leads to a ZeroDivisionError. Instead of terminating the program, the handler in the except block now takes over and sets x to infinity, a floating point number larger than representable by Python.