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。
发布于 2020-06-08 06:26:09
区别在于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的实例,而不是派生类型。
也见this answer。
https://stackoverflow.com/questions/62256118
复制相似问题