预计阅读本页时间:-
String Exceptions Are Right Out!
Prior to Python 2.6 and 3.0, it was possible to define exceptions with both class instances and string objects. String-based exceptions began issuing deprecation warnings in 2.5 and were removed in 2.6 and 3.0, so today you should use class-based exceptions, as shown in this book. If you work with legacy code, though, you might still come across string exceptions. They might also appear in tutorials and web resources written a few years ago (which qualifies as an eternity in Python years!).
String exceptions were straightforward to use—any string would do, and they matched by object identity, not value (that is, using is, not ==):
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
C:\misc> C:\Python25\python
>>> myexc = "My exception string" # Were we ever this young?
>>> try:
... raise myexc
... except myexc:
... print('caught')
...
caught
This form of exception was removed because it was not as good as classes for larger programs and code maintenance. Although you can’t use string exceptions today, they actually provide a natural vehicle for introducing the class-based exceptions model.