繁体   English   中英

如何捕获Python中的嵌套函数调用已捕获的异常

[英]How to catch an exception that was already caught by a nested function call in Python

在下面的示例中,我希望能够从a()调用函数b() a() ,并使a()识别出b()发生了IndexError

def a():
    try:
        b()
    except IndexError:
        print('Caught the error in a!')

def b():
    array = ["First", "Second"]

    try:
        print(array[2])
    except IndexError:
        print('Caught the error in b!')

a()

该脚本的输出如下所示:

Caught the error in b!

我希望看到的是此脚本输出以下内容的一种方式:

Caught the error in b!
Caught the error in a!

我非常希望有一个约束条件的答案,即只能针对我实际上正在处理的特定实际场景对函数a()进行修改,但是如果不可能,则将接受另一个答案。

我的(不正确的)直觉假定脚本只是在b()捕获了异常之后终止了,但是下面的示例证明事实并非如此:

def a():
    try:
        b()
    except IndexError:
        print('Caught the error in a!')
    print('Both chances are over now.')

def b():
    array = ["First", "Second"]

    try:
        print(array[2])
    except IndexError:
        print('Caught the error in b!')

a()

该脚本将输出以下内容:

Caught the error in b!
Both chances are over now.

这向我证明了a()函数将在b()发生IndexError异常后继续执行。

def a():
    try:
        b()
    except IndexError:
        print('Caught the error in a!')
    print('Both chances are over now.')

def b():
    array = ["First", "Second"]

    try:
        print(array[2])
    except IndexError:
        print('Caught the error in b!')
        raise

a()

<exception> as eraise <exception> from e

def a():
    try:
        b()
    except IndexError:
        print('Caught the error in a!')
    print('Both chances are over now.')

def b():
    array = ["First", "Second"]

    try:
        print(array[2])
    except IndexError as e:
        raise IndexError('Caught the error in b!') from e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM