Python possible to run while loop until RuntimeError: maximum recursion depth exceeded while calling a Python object

error-handling, python, recursion, runtime, runtime-error

Solution

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.

Problem

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!

Original source