预计阅读本页时间:-
Chapter 33. Exception Coding Details
In the prior chapter we took a quick look at exception-related statements in action. Here, we’re going to dig a bit deeper—this chapter provides a more formal introduction to exception processing syntax in Python. Specifically, we’ll explore the details behind the try, raise, assert, and with statements. As we’ll see, although these statements are mostly straightforward, they offer powerful tools for dealing with exceptions in Python code.
Note
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
One procedural note up front: The exception story has changed in major ways in recent years. As of Python 2.5, the finally clause can appear in the same try statement as except and else clauses (previously, they could not be combined). Also, as of Python 3.0 and 2.6, the new with context manager statement has become official, and user-defined exceptions must now be coded as class instances, which should inherit from a built-in exception superclass. Moreover, 3.0 sports slightly modified syntax for the raise statement and except clauses. I will focus on the state of exceptions in Python 2.6 and 3.0 in this edition, but because you are still very likely to see the original techniques in code for some time to come, along the way I’ll point out how things have evolved in this domain.