提出错误类与类的实例相比有什么优缺点

时间:2017-07-04 15:43:03

标签: python python-3.x

以下似乎具有相同的效果:

>>> raise NotImplementedError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError

>>> raise NotImplementedError()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError

是否存在差异,如果有,每种方法的优缺点是什么?

2 个答案:

答案 0 :(得分:5)

如果异常类不需要初始化参数,则基本上没有区别:

  

如果传递了异常,则会隐式实例化   调用没有参数的构造函数。

[强调我的]

否则,您将收到另一个抱怨实例初始化的异常:

Traceback (most recent call last):
  File "python", line 6, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)
>>> raise ValueError('number must be 42')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: number must be 42

显然,您可以通过将自定义参数传递给自定义异常类或将自定义消息传递给内置异常类来执行更多操作:

ValueError

上述内容比贫瘠的{{1}}更具信息性(从用户的角度来看非常可取)。

答案 1 :(得分:1)

没有区别:

>>> try:
...     raise NotImplementedError
... except Exception as e:
...     pass
...
>>> e
NotImplementedError()
>>> type(e)
<type 'exceptions.NotImplementedError'>
>>> type(NotImplementedError)
<type 'type'>
>>> type(NotImplementedError())
<type 'exceptions.NotImplementedError'>
>>>

请参阅文档的第8.4节:https://docs.python.org/3/tutorial/errors.html#raising-exceptions