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

So, I have a class with two methods:

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(xf()) 

and outputs:

 ... forever None 10 

What gives? Why can I return from one but the other? I can print normally from the first, except, but it always returns None

+6
source share
1 answer

Because the cycle() method is recursive, but when you call it recursively, you are not returning the result returned by the recursive call.

So, inside self.cycle() , let's say you call self.cycle() again, and then when you try to call self.cycle() , a RuntimeError occurs, so the call returns 10 back to the first call to self.cycle() , but this one (say, the first self.cycle() ) call does not return this result back to the caller, so the result returned by the second self.cycle() is lost, and you return None .

If you return the result of calling self.cycle() , you should get the correct result. Example -

 >>> 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 

Please note: I set the recursion limit to 3 so that the recursion depth exceeds the error after three recursion levels.

+4
source

All Articles