处理超出最大递归深度

Joh*_*raz 4 python error-handling recursion python-3.x

我创建了一个程序,使用递归来解决简单的迷宫.如果有一个相当复杂的迷宫,我会得到一个最大的递归深度误差.我在这个网站上搜索了这个错误并阅读了帖子,所以我相信我对正在发生的事情有一个大致的了解.

与我看到的其他线程不同,我不是试图增加递归限制.sys.setrecursionlimit()不是我要找的.我希望能够处理溢出,而不是崩溃让程序打印消息(print("Sorry but this maze solver was not able to finish analyzing the maze due to recursion limits))并关闭.

我知道使用try和除了处理错误,但我不确定我是否可以合并它来处理最大递归深度错误.

Mar*_*ers 7

最大递归深度误差只是另一个例外; 你可以捕获RecursionError异常(Python 3.5或更高版本):

try:
    solveMaze(maze)
except RecursionError as re:
    print('Sorry but this maze solver was not able to finish '
          'analyzing the maze: {}'.format(re.args[0]))
Run Code Online (Sandbox Code Playgroud)

我已经附加了运行时异常附带的错误消息; 对于递归错误maximum recursion depth exceeded.

如果你需要支持3.5之前的Python版本,你可以捕获基类RuntimeError.如果您担心捕获不是递归深度错误的运行时错误,您可以内省该.args[0]值:

try:
    solveMaze(maze)
except RuntimeError as re:
    if re.args[0] != 'maximum recursion depth exceeded':
        # different type of runtime error
        raise
    print('Sorry but this maze solver was not able to finish '
          'analyzing the maze: {}'.format(re.args[0]))
Run Code Online (Sandbox Code Playgroud)

演示选项:

>>> def infinity(): return infinity()
... 
>>> try:
...     infinity()
... except RecursionError as re:
...     print('Oopsie: {}'.format(re.args[0]))
... 
Oopsie: maximum recursion depth exceeded
>>> def alter_dict_size():
...     dct = {'foo': 'bar'}
...     for key in dct:
...         del dct['foo']
... 
>>> try:
...     alter_dict_size()
... except RuntimeError as re:
...     print('Oopsie: {}'.format(re.args[0]))
... 
Oopsie: dictionary changed size during iteration
>>> try:
...     infinity()
... except RuntimeError as re:
...     if re.args[0] != 'maximum recursion depth exceeded':
...         raise
...     print('Oopsie: {}'.format(re.args[0]))
... 
Oopsie: maximum recursion depth exceeded
>>> try:
...     alter_dict_size()
... except RuntimeError as re:
...     if re.args[0] != 'maximum recursion depth exceeded':
...         raise
...     print('Oopsie: {}'.format(re.args[0]))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 3, in alter_dict_size
RuntimeError: dictionary changed size during iteration
Run Code Online (Sandbox Code Playgroud)

更改字典大小也会引发RuntimeError异常,但测试生成的异常消息可以区分.