【发布时间】:2023-02-23 02:11:30
【问题描述】:
请参阅以下示例:
def a(test):
if test > 1:
raise Exception("error in 'a'")
print("nothing happened")
def b(test):
if test > 1:
raise Exception("error in 'b'")
print("nothing happened")
def c(test):
if test > 1:
raise Exception("error in 'c'")
print("nothing happened")
def all():
try:
a(1)
except Exception:
print("finished due to error")
return False
try:
b(2)
except Exception:
print("finished due to error")
return False
try:
c(1)
except Exception:
print("finished due to error")
return False
if __name__ == "__main__":
all()
输出为:
nothing happened
finished due to error
所以我想要实现的是 all() 在任何内部函数失败时完成,返回 False。
有没有办法像这样编写all()函数,从内部修改内部函数,以便它们将“return False”传递给外部函数?
def all():
a(1)
b(2)
c(1)
(目前的输出是):
Traceback (most recent call last):
File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 24, in <module>
all()
File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 18, in all
b(2)
File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 8, in b
raise Exception("error in 'b'")
Exception: error in 'b'
nothing happened
目标是获得与第一个输出类似的输出,但没有围绕每个函数的所有 try - except 逻辑。
非常感谢
【问题讨论】:
-
仅供参考,已经有一个名为
all()的内置函数,您应该为您的函数使用不同的名称。 -
遍历函数,在循环内放置一个 try-except,在 except 主体中放置一个
return False。 -
不可以。您可以不捕获异常,但不能强制隐式返回。
标签: python python-3.x