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

cam*_*mil 1 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
Run Code Online (Sandbox Code Playgroud)

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

Mos*_*oye 5

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

如果传递了一个异常,它将通过调用没有参数的构造函数来隐式实例化.

[ 强调我的 ]

否则,你会得到另一个抱怨实例初始化的异常:

class MyException(Exception):
   def __init__(self, arg):
      pass

raise MyException
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
  File "python", line 6, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

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

>>> raise ValueError('number must be 42')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: number must be 42
Run Code Online (Sandbox Code Playgroud)

从荒芜的角度来看,上述内容更为丰富(从用户的角度来看非常可取)ValueError.