gpt4 book ai didi

python - 如何跳出父函数?

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:52 26 4
gpt4 key购买 nike

如果我想跳出一个函数,我可以调用return

如果我在子函数中并且我想跳出调用子函数的父函数怎么办?有办法做到这一点吗?

一个最小的例子:

def parent():
print 'Parent does some work.'
print 'Parent delegates to child.'
child()
print 'This should not execute if the child fails(Exception).'

def child():
try:
print 'The child does some work but fails.'
raise Exception
except Exception:
print 'Can I call something here so the parent ceases work?'
return
print "This won't execute if there's an exception."

最佳答案

这是异常处理的目的:

def child():
try:
print 'The child does some work but fails.'
raise Exception
except Exception:
print 'Can I call something here so the parent ceases work?'
raise Exception # This is called 'rethrowing' the exception
print "This won't execute if there's an exception."

然后父函数将不会捕获异常,它会继续在堆栈中向上移动,直到找到捕获异常的人。

如果你想重新抛出相同的异常,你可以使用raise:

def child():
try:
print 'The child does some work but fails.'
raise Exception
except Exception:
print 'Can I call something here so the parent ceases work?'
raise # You don't have to specify the exception again
print "This won't execute if there's an exception."

或者,您可以将 Exception 转换为更具体的内容,方法是说 raise ASpecificException

关于python - 如何跳出父函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com