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.try
clause contains code that could cause more than one potential error, as in the following program?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).except
clauses following try
, and you can tell which exception you want to handle: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())
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).sys.exc_info()
method.