为了账号安全,请及时绑定邮箱和手机立即绑定

Python 崩溃而不是引发异常

Python 崩溃而不是引发异常

蝴蝶不菲 2021-08-24 17:40:53
我写了这个程序: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 funFile "<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但是当代码出错时,程序就会崩溃。谁能向我解释为什么会发生这种情况?
查看完整描述

1 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

是的,你在同名的函数中调用你的函数,导致你陷入递归的兔子洞(一个调用自身的函数)而没有逃逸


def fun():

 try: 1/0

 except: fun()

这意味着当您调用fun()if1/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()


查看完整回答
反对 回复 2021-08-24
  • 1 回答
  • 0 关注
  • 290 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号