Python 提供了广泛的 list of built-in exceptions .
在我看来,大多数内置异常只能由解释器或 Python 的内置函数引发。
那么,这些内置异常中的哪些应该在用户代码中引发? Python 2.7 和 3.x 之间的指南是否不同?
来自 .NET,我认为这是一个重要的问题。对于 .NET,Microsoft 在 Using Standard Exception Types 中提供了关于抛出和不抛出哪些异常的明确指导.
对于 Python,在我看来,从直觉和示例来看,以下内置异常适合在用户代码中引发:
IndexError
LookupError
NotImplementedError
TypeError
ValueError
...但这些不会,因为每个都表示一种系统故障:
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
MemoryError
OSError
请您参考如下方法:
对于可以从用户代码引发的异常,Python 程序员有很大的灵 active 。然而,这种灵 active 并不意味着“一切皆有可能”。来自 Python 标准库的第 3 版文档,文章 5. Built-in Exceptions提供此一般性指导。
程序员可以抛出哪些异常:
User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error. (emphasis mine)
关于程序员定义的异常:
The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException. More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions.
条款5.1. Base classes建议通常不引发基类异常:
The following exceptions are used mostly as base classes for other exceptions.
BaseException, Exception, ArithmeticError, BufferError, LookupError
相反,根据条款 5.2. Concrete exceptions 中的指导,通常应该提出的是具体异常(exception):
The following exceptions are the exceptions that are usually raised.
AssertionError, AttributeError, EOFError, ... OSError, ..., ZeroDivisionError
因此,例如,与其引发 ArithmeticError,不如考虑引发其派生类之一:FloatingPointError、OverflowError 和 零除法错误。 (或者,也许是您从 ArithmeticError 派生的类。)
(有关 OSError 的更多信息,请参见子句 5.2.1. OS exceptions。)
最后,关于文章 29.5. warnings — Warning control 中的警告信息 :
Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module.
...
User code can define additional warning categories by subclassing one of the standard warning categories. A warning category must always be a subclass of the Warning class.
