User-Defined Exceptions

The raise statement introduced in the prior section raises a built-in exception defined in Python’s built-in scope. As you’ll learn later in this part of the book, you can also define new exceptions of your own that are specific to your programs. User-defined exceptions are coded with classes, which inherit from a built-in exception class: usually the class named Exception. Class-based exceptions allow scripts to build exception categories, inherit behavior, and have attached state information:

>>> class Bad(Exception):                 # User-defined exception
...     pass
...
>>> def doomed():
...     raise Bad()                       # Raise an instance
...
>>> try:
...     doomed()
... except Bad:                           # Catch class name
...     print('got Bad')
...
got Bad
>>>

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元