Since we’re at the end of Part I, we’ll just work on a few short exception exercises to give you a chance to play with the basics. Exceptions really are a simple tool, so if you get these, you’ve got exceptions mastered.
try/except. Write a function called
oops
that explicitly raises a
IndexError
exception when called. Then write
another function that calls oops
inside a
try/except
statement to catch the error. What
happens if you change oops
to raise
KeyError
instead of IndexError
?
Where do the names KeyError
and
IndexError
come from? (Hint: recall that all
unqualified names come from one of three scopes, by the LGB rule.)
Exception lists. Change the
oops
function you just wrote to raise an exception
you define yourself, called MyError
, and pass an
extra data item along with the exception. Then, extend the
try
statement in the catcher function to catch
this exception and its data in addition to
IndexError
, and print the extra data item.
Error handling. Write a function called
safe(func,
*args)
that runs any
function using apply
, catches any exception raised
while the function runs, and prints the exception using the
exc_type
and exc_value
attributes in the sys
module. Then, use your
safe
function to run the oops
function you wrote in Exercises 1 and/or 2. Put
safe
in a module file called
tools.py, and pass it the
oops
function interactively. What sort of error
messages do you get? Finally, expand safe
to also
print a Python stack trace when an error occurs by calling the
built-in print_exc()
function in the standard
traceback
module (see the Python library reference
manual or other Python books for details).