我创建了一个程序,使用递归来解决简单的迷宫.如果有一个相当复杂的迷宫,我会得到一个最大的递归深度误差.我在这个网站上搜索了这个错误并阅读了帖子,所以我相信我对正在发生的事情有一个大致的了解.
与我看到的其他线程不同,我不是试图增加递归限制. sys.setrecursionlimit()不是我要找的.我希望能够处理溢出,而不是崩溃让程序打印一条消息(打印(“抱歉,但这个迷宫求解器由于递归限制无法完成对迷宫的分析)”并关闭.
我知道使用try和除了处理错误,但我不确定我是否可以合并它来处理最大递归深度错误.
解决方法:
最大递归深度误差只是另一个例外;你可以捕获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]))
我已经附加了运行时异常附带的错误消息;对于超出最大递归深度的递归错误.
如果需要支持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 "", line 2, in
File "", line 3, in alter_dict_size
RuntimeError: dictionary changed size during iteration
更改字典大小也会引发RuntimeError异常,但测试生成的异常消息可以区分.
标签:python,python-3-x,recursion,error-handling