8.6. 用户自定义异常

程序可以通过创建新的异常类来命名它们自己的异常(有关Python 类的更多信息,请参阅 )。异常通常应该直接或间接地从 Exception 类派生。

可以定义异常类,它可以执行任何其他类可以执行的任何操作,但通常保持简单,只提供一些属性,这些属性允许处理程序为异常提取有关错误的信息。 在创建可能引发多个不同错误的模块时,通常的做法是为该模块定义的异常创建基类,并为不同错误条件创建特定异常类的子类:

  1. class Error(Exception):
  2. """Base class for exceptions in this module."""
  3. pass
  4. class InputError(Error):
  5. """Exception raised for errors in the input.
  6. Attributes:
  7. expression -- input expression in which the error occurred
  8. message -- explanation of the error
  9. """
  10. def __init__(self, expression, message):
  11. self.expression = expression
  12. self.message = message
  13. class TransitionError(Error):
  14. """Raised when an operation attempts a state transition that's not
  15. allowed.
  16. Attributes:
  17. previous -- state at beginning of transition
  18. next -- attempted new state
  19. message -- explanation of why the specific transition is not allowed
  20. """
  21. def __init__(self, previous, next, message):
  22. self.previous = previous
  23. self.next = next
  24. self.message = message

大多数异常都定义为名称以“Error”结尾,类似于标准异常的命名。

许多标准模块定义了它们自己的异常,以报告它们定义的函数中可能出现的错误。有关类的更多信息,请参见 章节。