我很好奇python中是否有一种方法可以在try/catch块中继续,在捕获异常之后,查看它的属性,如果不相关,则继续向下堆栈。在
try:
# Code
except AppleError as apple_ex:
# look at 'apple_ex.error_code' error body, and if not relevant,
# continue on to next down the catch block...
# In other words, proceed to except BananaError and so on down.
except BananaError as banana_ex:
# ...
except Exception as ex:
# ...
不,那是不可能的。在异常由内部
except
处理后,外部except
无法处理:在
try
语句上的Fromthe docs:简而言之,您唯一的解决方案可能是在外部级别使用另一个处理程序,并在内部处理程序中重新生成异常,即:
现在,嵌套的
except
引发一个异常,该异常随后被类似的处理程序捕获。在这不是Python中处理异常的方式。当您在try块中引发异常时,如果您在
except
中处理捕捉异常,它将位于该块内,但不会继续到同一级别的下一个except
。请注意以下功能示例:所以,在你的
try
中,我们提出一个AttributeError
,我们抓住它,然后在AttributeError
内部提升一个TypeError
。在except TypeError
将而不是捕获TypeError
。在根据您如何解释您的问题,您需要重新思考如何处理异常,并查看是否可以确定其他地方的错误处理,并在那里提出错误。在
例如:
^{pr2}$AppleError仍然是AppleError而不是BananaError,即使error_代码与之无关,因此陷入BananaError是没有意义的。在
您可以为不同的错误代码定义特定的错误:
然后您可以尝试匹配特定错误:
^{pr2}$如果您不想区分不同类型的apple错误,您仍然可以捕获所有apple错误:
例如,您可以将这些组合起来,例如,只对Grannymith进行特殊处理,而不针对Macintosh:
重要的是列出从最具体到最不具体的错误。如果在grannymitherror之前测试AppleError,那么它永远不会进入grannymith块。在
相关问题 更多 >
编程相关推荐