简体   繁体   中英

Try and Except on RuntimeError in Python not catching the Error

I have a recursion function which gives this error "RuntimeError: maximum recursion depth exceeded in cmp" when I use a number beyond a limit. I am looking to make the except block return -1 (which is the requirement) and The control is not being transferred to the except block. Please do let me know as to what is wrong my program. Thanks in advance

def g(n):
        try:
        def f(x):
            if x == 1:
                return 1
            elif x == 0.5:
                return math.sqrt(PI)
            else:
                final_value = (x-1)*f(x-1)
                return final_value
    except RuntimeError:
        return -1            

    n = f(n/2.0)
    return n

The only thing inside your try (ignoring the IndentationError , which hopefully isn't there in your real code) is a def statement. Defining the function doesn't raise a RuntimeError , so there's nothing to catch.

Calling the function raises a RuntimeError , so you need the try around a call to the function. The two obvious places are the recursive call:

try:
    final_value = (x-1)*f(x-1)
except RuntimeError:
    return -1
return final_value

… or around the outer call:

try:
    n = f(n/2.0)
except RuntimeError:
    return -1
return n

I don't know which one you want. Handling it in the outer call means all 1000 recursive frames get thrown away and you just return -1 from the top level. Handling it in the inner call means you return -1 from the innermost frame, but then each frame from there to the top multiplies the -1 by its local x-1 before passing it back up. Hopefully you know which one of those you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM