8.5. 用户自定义异常

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

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

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

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

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