gpt4 book ai didi

python - 使用 Python 异常层次结构

转载 作者:太空宇宙 更新时间:2023-11-04 05:54:57 25 4
gpt4 key购买 nike

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 anexception handler or to report an error condition “just like” thesituation in which the interpreter raises the same exception; butbeware that there is nothing to prevent user code from raising aninappropriate error. (emphasis mine)

关于程序员定义的异常:

The built-in exception classes can be subclassed to define newexceptions; programmers are encouraged to derive new exceptions fromthe Exception class or one of its subclasses, and not fromBaseException. More information on defining exceptions isavailable in the Python Tutorial under User-defined Exceptions.

条款5.1. Base classes建议通常引发基类异常:

The following exceptions are used mostly as base classes for otherexceptions.

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,不如考虑引发其派生类之一:FloatingPointErrorOverflowError零除法错误。 (或者,也许是您从 ArithmeticError 派生的类。)

(有关 OSError 的更多信息,请参见子句 5.2.1. OS exceptions。)

最后,关于文章 29.5. warnings — Warning control 中的警告信息 :

Warning messages are typically issued in situations where it is usefulto alert the user of some condition in a program, where that condition(normally) doesn’t warrant raising an exception and terminating theprogram. For example, one might want to issue a warning when a programuses an obsolete module.

...

User code can define additional warning categories by subclassing oneof the standard warning categories. A warning category must always bea subclass of the Warning class.

关于python - 使用 Python 异常层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com