Reputation: 411
I wrote this program:
def fun():
try: 1/0
except: fun()
fun()
I thought that I will get an exception, but instead, I got the following fatal error:
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
(the File "<stdin>", line 3 in fun
line is shown 98 times) and then the program crushes (instead of raising an exception).
I don't really get why this happens. When I run the above program without errors it just raises an exception:
def fun():
fun()
fun()
Raises the following exception:
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
But when the code is erroneous, the program just crashes.
Can anyone explain to me why this happens?
Upvotes: 1
Views: 2603
Reputation: 2939
Yes you call your function within the function of the same name leading you down a rabbit hole of recursion (a function calling itself) with no escape
def fun():
try: 1/0
except: fun()
This means that when you call fun()
if 1/0
raises an error it will move to the except
branch and call the function fun which if 1/0
raises an error it will move to the except
branch and call the function fun which if 1/0
raises an error it will move to the except
branch and call the function fun which if 1/0
raises an error it will move to the except
branch and call the function fun which...
If you get the picture.
So if it's error handling you are learning you might simple want to return some value like:
def fun():
try:
1/0
except:
return "Error handling worked"
fun()
Upvotes: 1