2014-12-05 164 views
3

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

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

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

+0

请注意,您通常可以将任何递归算法实现为使用队列数据结构的非递归算法。这是解决递归限制的一种方法。 – jme 2014-12-05 17:45:48

+0

嗨,谢谢JME的信息。我需要为这个任务使用递归(这是一个类的问题) – JohnKraz 2014-12-05 18:11:08

回答

3

最大递归深度错误只是另一个例外;你可以赶上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。如果你担心赶上那些递归深度错误运行时错误,你可以内省.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异常,但测试生成的异常消息可以让您区分。

+0

如果你想捕捉递归错误,赶上'RecursionError'! – 2018-01-25 15:38:32

+0

@SolomonUcko:谢谢你指出。这是一个* new *异常,在Python 3.5中添加,最初于2015年9月发布。我已将它添加到我的答案中。 – 2018-01-25 18:16:10