最大遞歸深度錯誤只是另一個例外;你可以趕上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
異常,但測試生成的異常消息可以讓您區分。
請注意,您通常可以將任何遞歸算法實現爲使用隊列數據結構的非遞歸算法。這是解決遞歸限制的一種方法。 – jme 2014-12-05 17:45:48
嗨,謝謝JME的信息。我需要爲這個任務使用遞歸(這是一個類的問題) – JohnKraz 2014-12-05 18:11:08