I'm running a recursive loop to achieve the maximum optimization for something and am reaching a point where the code hits a RuntimeError: maximum recursion depth exceeded while calling a Python objec
t. This is expected, but I want to stop the code right at the point before it hits that error, so I can view my data at that point.
Is it possible to have a while loops saying something similar to that? Something like "Hey, run this loop until you reach maximum recursion depth. Once reached, stop and return."
Thanks for the help!
You can do the following
def recurse():
try:
recurse()
except RuntimeError as e:
if e.message == 'maximum recursion depth exceeded while calling a Python object':
# don't recurse any longer
else:
# something else went wrong
http://docs.python.org/tutorial/errors.html
NOTE: it might be worth while to find out the error number of the max recursion depth error and check for that instead of the error string.
Perhaps, have the recursive call in a try/except RuntimeError block? When the except is called return the value.
EDIT: Yes this is possible, like so:
def recursion(i):
try:
return recursion(i+1)
except RuntimeError:
return i
a=0
print recursion(a)
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