如何在Python中检测超出最大递归深度异常?

7
try:
    recursive_function()
except RuntimeError e:
    # is this a max. recursion depth exceeded exception?

如何判断已达到最大递归深度?

1个回答

8

您可以查看异常本身:

>>> def f():
...     f()
... 
>>> try:
...     f()
... except RuntimeError as re:
...     print re.args, re.message
... 
('maximum recursion depth exceeded',) maximum recursion depth exceeded

我认为你无法区分这个和仅仅假装是递归深度超出(运行时)异常的东西。`message`已经被弃用,所以`args`可能是最好的选择,并且与Python 3兼容。
更新:在Python 3.5中,有一个特定的`RecursionError`可以捕获。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接