2014-12-05 169 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