Exception Functions

The sys module provides one function that provides the details of the exception that was raised. Programs with exception handling will occasionally use this function.

The sys.exc_info function returns a 3-tuple with the exception, the exception's parameter, and a traceback object that pinpoints the line of Python that raised the exception. This can be used something like the following not-very-good example.

Example 17.5. exception2.py

import sys
import math
a= 2
b= 2
c= 1
try:
    x1= (-b+math.sqrt(b*b-4*a*c))/(2*a)
    x2= (-b-math.sqrt(b*b-4*a*c))/(2*a)
    print x1, x2
except:
    e,p,t= sys.exc_info()
    print e,p

This uses multiple assignment to capture the three elements of the sys.exc_info tuple, the exception itself in e, the parameter in p and a Python traceback object in t.

This "catch-all" exception handler in this example is a bad policy. It may catch exceptions which are better left uncaught. We'll look at these kinds of exceptions in the section called “Built-in Exceptions”. For example, a RuntimeError is something you should not bother catching.