[英]Python crashes instead of raising an exception
我写了这个程序:
def fun():
try: 1/0
except: fun()
fun()
我以为我会得到一个例外,但是,我收到了以下致命错误:
Fatal Python error: Cannot recover from stack overflow.
Current thread 0x00003bec (most recent call first):
File "<stdin>", line 2 in fun
File "<stdin>", line 3 in fun
( File "<stdin>", line 3 in fun
行中的File "<stdin>", line 3 in fun
行显示了98次),然后程序崩溃了(而不是引发异常)。
我真的不明白为什么会这样。 当我运行上面的程序而没有错误时,它只会引发一个异常:
def fun():
fun()
fun()
引发以下异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fun
File "<stdin>", line 2, in fun
File "<stdin>", line 2, in fun
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
但是,如果代码错误,程序就会崩溃。
谁能向我解释为什么会这样?
是的,您可以在同名功能内调用您的功能,从而使您顺利进行递归的兔子漏洞(一个自称功能的功能)
def fun():
try: 1/0
except: fun()
这意味着当您调用fun()
如果1/0
引发错误时,它将移至except
分支,并调用函数fun;如果1/0
引发错误,它将移至except
分支并调用函数fun,如果1/0
引发错误,它将移至except
分支并调用函数fun;如果1/0
引发错误,则将移至except
分支并调用函数fun,...
如果您知道图片。
因此,如果您正在处理错误,则可能只是想返回一些值,例如:
def fun():
try:
1/0
except:
return "Error handling worked"
fun()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.