我玩弄了一个异常层次结构并意识到 未捕获具有多个父类的异常子类。
例如:
class Error1(Exception):
pass
class Error2(Exception):
pass
class MixedError(Error1, Error2):
pass
try:
print('before 1')
raise Error2()
print('after 1')
except MixedError:
print('Caught it with a mixin 1!')
except Exception:
print('Big catcher here 1!')
这打印:
before 1
Big catcher here 1!
为什么没有捕获到多父异常?
最佳答案
您误解了异常
的工作原理。异常由父异常缓存,而不是由子异常缓存:
class Error1(Exception):
pass
class Error2(Exception):
pass
class MixedError(Error1, Error2):
pass
try:
print('before 1')
raise MixedError()
print('after 1')
except Error2:
print('Caught it with a Error2!')
except Exception:
print('Big catcher here 1!')
打印:
before 1
Caught it with a Error2!
关于python - 为什么没有捕获到多父异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50136746/