首页 > 解决方案 > 在 Python 中捕获外部异常

问题描述

我的代码试图做某事,但它触发了一个错误...触发另一个错误。因此,错误消息如下所示:

SillyError: you can`t do that becuz blablabla

The above exception was the direct cause of the following exception:

LoopyError: you can`t do that becuz blobloblo 

我想创建一个try except仅捕获此特定错误二重奏的块。但是,我只能抓住第一个,因为一旦我抓住了,第二个就没有机会触发了。

另一个问题是关于捕获任何一个异常,但我只想在两个异常都被连续触发时才捕获。有办法吗?

标签: python-3.xexception

解决方案


如果您有 try\except,您将始终根据外部异常捕获错误。但是,您确实可以选择传递您不想处理的任何异常。

在此代码中,ZeroDivisionError 被捕获并包装在另一个异常中,然后由调用代码捕获。调用代码检查内部异常并决定是否在堆栈中重新引发异常。

def xtest():
    try:
        a = 1/0  # exception - division by zero
    except ZeroDivisionError as e:
        raise Exception("Outer Exception") from e  # wrap exception (e not needed for wrap)

try:
   xtest()
except Exception as ex:
   print(ex)  # Outer Exception
   print(ex.__cause__)  # division by zero
   
   if (str(ex) == "Outer Exception" and str(ex.__cause__) == "division by zero"):
       print("Got both exceptions")
   else:
       raise # pass exception up the stack

只是为了完成,您还可以根据异常类名称进行检查:

   if (type(ex).__name__ == "Exception" and type(ex.__cause__).__name__ == "ZeroDivisionError"):
       print("Got both exceptions")

@ShadowRanger 指出只检查类类型而不是类名可能会更快:

   if (type(ex) == Exception and type(ex.__cause__) == ZeroDivisionError):
       print("Got both exceptions")

推荐阅读