如何检测最大值 递归深度超过了Python中的异常?

Jay*_*Jay 7 python

try:
    recursive_function()
except RuntimeError e:
    # is this a max. recursion depth exceeded exception?
Run Code Online (Sandbox Code Playgroud)

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

DSM*_*DSM 8

您可以查看异常本身:

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

我不认为你可以区分这个和仅仅假装是递归深度超过(运行时)异常的东西. message不推荐使用,因此args可能是最好的选择,并且兼容Python-3.


更新:在Python 3.5中,有一个特定的RecursionError,你可以捕获.