As mentioned earlier, Python throws an error or exception whenever things do not go to plan. Fortunately, when this happens, a well-coded program knows how to handle these errors and can "catch" the error. This is sometimes called "trapping". To catch the error, one must be a bit less forceful with one's commands and use the try...except program structure.
To use the first exception from the previous page, we know that we get a NameError if we try
print a
If we want to ensure that the whole house of code does not fall down on us, we can couch the print statement in a try clause and handle the exception with except:
try:
print a
except:
print "Doh, you need to define 'a' before you can print it!"
If you plug this into your Python shell, being sure to indent the arguments of try and except, you will get the following output:
Doh, you need to define 'a' before you can print it!Of course, this except clause handles every exception. What if you only want to process the NameError with that statement? Then tell Python to take exception at the NameError to the implicit exclusion of other types:
try: print a except NameError: print "Doh, you need to define 'a' before you can print it!"The output will be the same.
You can except any error in the module exceptions. In the section on the Python Library, there are lists of all exceptions and warnings.
