处理超出最大递归深度

时间:2014-12-05 17:23:39

标签: python python-3.x recursion error-handling

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

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

我知道使用try和except来处理错误,但我不确定是否可以将其合并以处理最大递归深度错误。

1 个答案:

答案 0 :(得分:7)

最大递归深度误差只是另一个例外;你可以捕获RecursionError exception(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]))

我已将附加到运行时异常的错误消息合并;对于maximum recursion depth exceeded的递归错误。

如果您需要支持3.5之前的Python版本,则可以捕获基类RuntimeError。如果您担心捕获 not 递归深度错误的运行时错误,您可以内省.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]))

选项演示:

>>> 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

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