[英]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.