Python 崩溃而不是引发异常

我写了这个程序:


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行显示 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

但是当代码出错时,程序就会崩溃。


谁能向我解释为什么会发生这种情况?




蝴蝶不菲
浏览 291回答 1
1回答

拉莫斯之舞

是的,你在同名的函数中调用你的函数,导致你陷入递归的兔子洞(一个调用自身的函数)而没有逃逸def fun():&nbsp;try: 1/0&nbsp;except: fun()这意味着当您调用fun()if1/0引发错误时,它将移动到except分支并调用函数 fun 如果1/0引发错误,它将移动到except分支并调用函数 fun 如果1/0引发错误它将移动到except分支并调用函数 fun 如果1/0引发错误,它将移动到except分支并调用函数 fun ......如果你得到图片。因此,如果您正在学习错误处理,则可能只想返回一些值,例如:&nbsp;def fun():&nbsp; &nbsp; &nbsp;try:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1/0&nbsp; &nbsp; &nbsp;except:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return "Error handling worked"fun()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python