So when toying with Python, I noticed that there is basically no limit on the program's stack size (kept performing power operations on a number, the precision stayed perfect even after getting to like thousands of digits). This makes me wonder: what if I accidentally got into an infinite recursive loop in Python? Would the compiler notice and throw a stack overflow error? Or would the program just crash? Would my CPU combust? This isn't something that I'd be eager to test myself, honestly.
No modern computer is going to combust due to user code, I promise. Try it for yourself:
def recurseInfinitely( n ):
recurseInfinitely(n+1)
recurseInfinitely(0)
Running this program promptly yields the output:
[...]
recurseInfinitely(n+1)
File "so.py", line 2, in recurseInfinitely
recurseInfinitely(n+1)
File "so.py", line 2, in recurseInfinitely
recurseInfinitely(n+1)
RuntimeError: maximum recursion depth exceeded
You can catch the error and check the value of n
:
def recurseInfinitely( n ):
try:
recurseInfinitely(n+1)
except RuntimeError:
print "We got to level %s before hitting the recursion limit."%n
And get:
We got to level 997 before hitting the recursion limit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With