从捕获 "RuntimeError" 返回总是给出 `None` python

Returning from caught "RuntimeError" always gives `None` python

所以我有一个 class,里面有两个方法:

class Test:
    def cycle(self, n=float("inf"), block="x"):
        try:            
            self.cycle(n-1, block)
        except RuntimeError as e:
            if str(e) == "maximum recursion depth exceeded":
                print("... forever")
                return 10
    def f(self):
        try: 
            raise Exception()
        except:
            return 10
        return 20


x = Test()
print(x.cycle())
print(x.f())

它输出:

... forever
None
10

什么给了?为什么我可以 return 来自一个除外而不是另一个?我也可以从第一个开始正常打印,但它总是 returns None

因为方法 cycle() 是递归的,但是当您递归调用它时,您不会 return 计算递归调用 return 的结果。

所以在 self.cycle() 里面,假设你再次调用 self.cycle() ,然后在尝试调用 self.cycle() 时发生 RuntimeError,所以调用 returns 10 返回到第一个 self.cycle() 调用,但是这个(比方说第一个 self.cycle() )调用不会 return 这个结果返回给它的调用者,所以结果 returned 由第二个 self.cycle() 丢失,你得到 returned None.

如果您 return 调用 self.cycle() 的结果,您应该会得到正确的结果。示例 -

>>> import sys
>>> sys.setrecursionlimit(3)
>>> class Test:
...     def cycle(self, n=float("inf"), block="x"):
...         try:
...             return self.cycle(n-1, block)
...         except RuntimeError as e:
...             if str(e) == "maximum recursion depth exceeded":
...                 print("... forever")
...                 return 10
...
>>> t = Test()
>>> print(t.cycle())
... forever
10

请注意,我将递归限制设置为3,以便递归3级后出现递归深度超出错误。