Skip to main content
 首页 » 编程设计

python之引发错误类与类实例的优缺点是什么

2025年05月04日17dyllove98

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

>>> 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 

有区别吗?如果有,各自的优缺点是什么?

请您参考如下方法:

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

If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments.

[强调我的]

否则,您将得到另一个提示实例初始化的异常:

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

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 信息量大得多(从用户的角度来看,这是非常可取的)。