异常与异常()

霸王金龙
print(Exception is Exception())
print(Exception == Exception())
print(type(Exception))
print(type(Exception())

try:
    raise Exception
except Exception:
    print("Caught Exception with Exception")
try:
    raise Exception()
except Exception:
    print("Caught Exception() with Exception")
try:
    raise Exception
except Exception():
    print("Caught Exception with Exception()")
try:
    raise Exception()
except Exception():
    print("Caught Exception() with Exception()")
>>> False
>>> False
>>> type
>>> Exception

>>> Caught Exception with Exception
>>> Caught Exception() with Exception
>>> TypeError: catching classes that do not inherit from BaseException is not allowed
>>> TypeError: catching classes that do not inherit from BaseException is not allowed

什么时候会使用一个?被调用的表单是否()有未调用不够用的用例?问题适用于任何异常,而不仅仅是Exception.

罗伊2012

区别在于它Exception是一个类型并且Exception()是该类的一个实例。

因此,当您引发异常时,您将引发该类的一个实例:

raise Exception("Something happened")

当您捕获异常时,您基本上是在说“这段代码将处理该类型的任何实例Exception”:

try: 
    raise Exception("Something happened")
except Exception as e: 
    print ("Caught an exception:", e) 

这也是您在问题中看到错误的原因:

>>> TypeError: catching classes that do not inherit from BaseException is not allowed

不允许您捕获不是Exception, 并且Exception()是 - 的实例Exception而不是派生类型的类型。

另请参阅此答案

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章