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

时间:2019-06-10 22:48:46

标签: python error-handling

在下面的示例中,我希望能够从b()调用函数a(),并使a()认识到IndexError已在{{ 1}}。

b()

此脚本的输出如下:

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()异常后,函数IndexError将继续执行。

2 个答案:

答案 0 :(得分:1)

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()

答案 1 :(得分:0)

使用<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