Exercises
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 aIndexError
exception when called. Then write another function that callsoops
inside atry/except
statement to catch the error. What happens if you changeoops
to raiseKeyError
instead ofIndexError
? Where do the namesKeyError
andIndexError
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, calledMyError
, and pass an extra data item along with the exception. Then, extend thetry
statement in the catcher function to catch this exception and its data in addition toIndexError
, and print the extra data item.Error handling. Write a function called
safe(func,
*args)
that runs any function usingapply
, catches any exception raised while the function runs, and prints the exception using theexc_type
andexc_value
attributes in thesys
module. Then, use yoursafe
function to run theoops
function you wrote in Exercises 1 and/or 2. Putsafe
in a module file called tools.py, and pass it theoops
function interactively. What sort of error messages do you get? Finally, expandsafe
to also print a Python stack trace when an error occurs by calling ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.