已读83%
预计阅读本页时间:-
预计阅读本页时间:-
Test Your Knowledge: Part VII Exercises
As we’ve reached the end of this part of the book, it’s time for a few exception exercises to give you a chance to practice the basics. Exceptions really are simple tools; if you get these, you’ve probably mastered exceptions.
See Part VII, Exceptions and Tools in Appendix B for the solutions.
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- try/except. Write a function called oops that explicitly raises an 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 a KeyError instead of an IndexError? Where do the names KeyError and IndexError come from? (Hint: recall that all unqualified names come from one of four scopes.)
- Exception objects and lists. Change the oops function you just wrote to raise an exception you define yourself, called MyError. Identify your exception with a class. Then, extend the try statement in the catcher function to catch this exception and its instance in addition to IndexError, and print the instance you catch.
- Error handling. Write a function called safe(func, *args) that runs any function with any number of arguments by using the *name arbitrary arguments call syntax, catches any exception raised while the function runs, and prints the exception using the exc_info call in the sys module. Then use your safe function to run your oops function from exercise 1 or 2. Put safe in a module file called tools.py, and pass it the oops function interactively. What kind 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 for details).
- Self-study examples. At the end of Appendix B, I’ve included a handful of example scripts developed as group exercises in live Python classes for you to study and run on your own in conjunction with Python’s standard manual set. These are not described, and they use tools in the Python standard library that you’ll have to research on your own. Still, for many readers, it helps to see how the concepts we’ve discussed in this book come together in real programs. If these whet your appetite for more, you can find a wealth of larger and more realistic application-level Python program examples in follow-up books like Programming Python and on the Web.