python:异常流:捕获后继续向下捕获块?

2024-09-30 00:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我很好奇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:
    # ...

Tags: andto方法apple属性堆栈onas
3条回答

不,那是不可能的。在异常由内部except处理后,外部except无法处理:

try语句上的Fromthe docs

When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

简而言之,您唯一的解决方案可能是在外部级别使用另一个处理程序,并在内部处理程序中重新生成异常,即:

try:
    try:
        raise ZeroDivisionError
    except ZeroDivisionError as e:
        print("caught")
        raise ZeroDivisionError
except ZeroDivisionError as f:
    print("caught")

现在,嵌套的except引发一个异常,该异常随后被类似的处理程序捕获。在

这不是Python中处理异常的方式。当您在try块中引发异常时,如果您在except中处理捕捉异常,它将位于该块内,但不会继续到同一级别的下一个except。请注意以下功能示例:

try:
    raise AttributeError()
except AttributeError:
    raise TypeError()
except TypeError:
    print("it got caught") # will not catch the TypeError raised above

所以,在你的try中,我们提出一个AttributeError,我们抓住它,然后在AttributeError内部提升一个TypeError。在

except TypeError而不是捕获TypeError。在

根据您如何解释您的问题,您需要重新思考如何处理异常,并查看是否可以确定其他地方的错误处理,并在那里提出错误。在

例如:

^{pr2}$

AppleError仍然是AppleError而不是BananaError,即使error_代码与之无关,因此陷入BananaError是没有意义的。在

您可以为不同的错误代码定义特定的错误:

GRANNY_SMITH_ERROR = 1
MACINTOSH_ERROR = 2
class AppleError(Exception): 
    def __init__(self, error_code, *args):
        super(AppleError, self).__init__(*args)
        self.error_code = error_code

class GrannySmithError(AppleError):
    def __init__(self, *args):
        super(GrannySmithError, self).__init__(GRANNY_SMITH_ERROR, *args)

class MacintoshError(AppleError):
    def __init__(self, *args):
        super(MacintoshError, self).__init__(MACINTOSH_ERROR, *args)

然后您可以尝试匹配特定错误:

^{pr2}$

如果您不想区分不同类型的apple错误,您仍然可以捕获所有apple错误:

try: raise MacintoshError()
except AppleError as exc: print("generic apple")

例如,您可以将这些组合起来,例如,只对Grannymith进行特殊处理,而不针对Macintosh:

try: raise MacintoshError()
except GrannySmithError as exc: print("granny smith")
except AppleError as exc: print("generic apple")

重要的是列出从最具体到最不具体的错误。如果在grannymitherror之前测试AppleError,那么它永远不会进入grannymith块。在

相关问题 更多 >

    热门问题