预计阅读本页时间:-
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
>>>