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
oopsthat explicitly raises aIndexErrorexception when called. Then write another function that callsoopsinside atry/exceptstatement to catch the error. What happens if you changeoopsto raiseKeyErrorinstead ofIndexError? Where do the namesKeyErrorandIndexErrorcome from? (Hint: recall that all unqualified names come from one of three scopes, by the LGB rule.)Exception lists. Change the
oopsfunction you just wrote to raise an exception you define yourself, calledMyError, and pass an extra data item along with the exception. Then, extend thetrystatement 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_typeandexc_valueattributes in thesysmodule. Then, use yoursafefunction to run theoopsfunction you wrote in Exercises 1 and/or 2. Putsafein a module file called tools.py, and pass it theoopsfunction interactively. What sort of error messages do you get? Finally, expandsafeto also print a Python stack trace when an error occurs by calling ...