[英]How to catch an exception that was already caught by a nested function call in Python
In the following example I would like to be able to call the function b()
from a()
, and for a()
to recognize that an IndexError
has occurred in b()
. 在下面的示例中,我希望能够从
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()
The output of this script looks like this: 该脚本的输出如下所示:
Caught the error in b!
What I would like to see is a way for this script to output the following: 我希望看到的是此脚本输出以下内容的一种方式:
Caught the error in b!
Caught the error in a!
I would greatly prefer an answer with the constraint that modifications only be made to the function a()
for the specific real-world scenario I'm actually dealing with, but will accept another answer if this isn't possible. 我非常希望有一个约束条件的答案,即只能针对我实际上正在处理的特定实际场景对函数
a()
进行修改,但是如果不可能,则将接受另一个答案。
My (incorrect) intuition would assume that the script is simply terminating after the exception is being caught in b()
, but the following example proves that this is not the case: 我的(不正确的)直觉假定脚本只是在
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()
This script will output the following: 该脚本将输出以下内容:
Caught the error in b!
Both chances are over now.
Which proves to me that the function a()
will continue executing after the IndexError
exception occurs in b()
. 这向我证明了
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()
Use <exception> as e
and raise <exception> from e
: 将
<exception> as e
并raise <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.