python - 处理超过最大递归深度

标签 python python-3.x recursion error-handling

我创建了一个使用递归来解决简单迷宫的程序。如果遇到相当复杂的迷宫,我会得到最大递归深度错误。我已经在该网站上搜索了该错误并阅读了线程,所以我相信我对发生的事情有一个大致的了解。

与我看到的其他线程不同,我没有尝试增加递归限制。 sys.setrecursionlimit() 不是我要找的。我希望能够处理溢出,而不是崩溃让程序打印一条消息(print(“抱歉,由于递归限制,这个迷宫求解器无法完成分析迷宫))并关闭。

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

最佳答案

最大递归深度错误只是另一个异常(exception);你可以 catch RecursionError exception (Python 3.5 或更高版本):

try:
    solveMaze(maze)
except RecursionError as err:
    print('Sorry but this maze solver was not able to finish '
          'analyzing the maze: {}'.format(err.args[0]))

我已经合并了附加到运行时异常的错误消息;对于 maximum recursion depth exceeded 的递归错误。

如果需要支持3.5之前的Python版本,可以抓到基类,RuntimeError .如果您担心捕获不是递归深度错误的运行时错误,您可以内省(introspection).args[0] 值:

try:
    solveMaze(maze)
except RuntimeError as err:
    if err.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(err.args[0]))

选项演示:

>>> def infinity(): return infinity()
... 
>>> try:
...     infinity()
... except RecursionError as err:
...     print('Oopsie: {}'.format(err.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 err:
...     print('Oopsie: {}'.format(err.args[0]))
... 
Oopsie: dictionary changed size during iteration
>>> try:
...     infinity()
... except RuntimeError as err:
...     if err.args[0] != 'maximum recursion depth exceeded':
...         raise
...     print('Oopsie: {}'.format(err.args[0]))
... 
Oopsie: maximum recursion depth exceeded
>>> try:
...     alter_dict_size()
... except RuntimeError as err:
...     if err.args[0] != 'maximum recursion depth exceeded':
...         raise
...     print('Oopsie: {}'.format(err.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 异常,但测试生成的异常消息可以让您区分。

关于python - 处理超过最大递归深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321416/

相关文章:

python - 在 Linux 中使用已编译的 Python shell

python - 更改 Pandas 数据框中特定列的数据类型

python - 我们可以为缓存函数中的 except 函数指定参数吗(在 Flask-Cache 中)

python - 如何在 python3 中将组织好的文件放入字典中?

python - 将图形转换为字典形式

python正则表达式查找至少包含一个字母的字母数字字符串

python - 翻译递归解决方案以查找列表的所有子集

python - 将 N 个点放入 M 个相等的箱子中

java - 为什么递归中值没有改变?

javascript - 如何折叠多维数组