这是我想要做的:
def bfunc():
try:
do_someting
except Exception as e:
return
def afunc():
bfunc()
xxx
def cfunc():
xxx
def main():
afunc()
cfunc()
在 bfunc() 中,我捕获了异常。现在在 main() 中,我想在发生异常时停止 afunc() 的执行,但继续执行 cfunc()。 我该怎么做,或者有没有其他方法可以在没有太多嵌套 try 语句的情况下捕获异常? 发送
答案 0 :(得分:0)
因为 bfunc()
是一个函数,因此,要停止 bfunc
的执行,您可以简单地使用 return
来停止 bfunc
。这不会影响 cfunc
,因为 return
只影响 bfunc
。
def bfunc():
try:
# do_someting
except Exception as e:
return # Exit the bfunc() immediately
您可以使用以下代码查看 print
是否有效
def bfunc():
try:
raise IndexError
except Exception as e:
return
def main():
bfunc()
print("Hello world")
if __name__ == "__main__":
main()
答案 1 :(得分:0)
只需将 try 异常块移动到 afunc
。它应该给你想要的效果。
def bfunc():
do_someting
def afunc():
try:
bfunc()
except Exception as e:
return
xxx #you can move it to try block in order to catch exceptions here too, but I don't know if it's what you like to do