最大递归深度错误只是另一个例外;你可以赶上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