Skip to main content

Section 12.3 Multiple Exceptions

What happens if your try clause contains code that could cause more than one potential error, as in the following program?
The user could enter non-numeric data (a ValueError), or they could enter zero for the number of customers, causing a ZeroDivideError. If we had only the generic except, we could not distinguish which error occurred, and would have to give a generic error message (which is not very helpful).
To solve this problem, Python lets you have multiple except clauses following try, and you can tell which exception you want to handle:
If you run the program again, entering, say five for the total dollars or zero for the number of customers, you will see the appropriate error message.

Subsection 12.3.1 Advanced Topic: Unanticipated Exceptions

What if you would like to catch any exception, yet still give an error message that yields a clue to the error?
Consider this program, which is a good example of an example, but not a particularly good use of exceptions (see Section 12.4 to see why). It will specifically catch a ValueError (bad input) or ZeroDivisionError, and everything else will be caught by the generic except.
import sys

try:
    numbers = [47, 13, 28, 0, 65]
    index = int(input("Enter index number:"))
    result = 1066 / numbers[index]
    print("Result is", result)
except ValueError:
    print("Index number must be numeric.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
except:
    print("Some unanticipated error occurred.")
    print(sys.exc_info())
The program starts with import sys, which imports functions that are useful when you need to find out information about the current Python system you are running on. It uses the sys.exc_info() method to return some information about the exception. It’s not pretty, but your program won’t crash. Try entering 9 for the index number to get an unanticipated exception (well, one that we purposely haven’t put into the program).

Note 12.3.1.

You will have to copy and paste this program into your development environment, as the activecode version of Python does not handle the sys.exc_info() method.