简体   繁体   English

尝试并在Python中的RuntimeError上尝试捕获错误

[英]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. 我有一个递归函数,当我使用超出限制的数字时,会出现此错误“ RuntimeError:最大递归深度超出cmp”。 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. 我希望使except块返回-1(这是要求),并且控件未转移到except块。 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. try的唯一事情(忽略IndentationError ,希望它在您的实际代码中不存在)是def语句。 Defining the function doesn't raise a RuntimeError , so there's nothing to catch. 定义该函数不会引发RuntimeError ,因此没有任何收获。

Calling the function raises a RuntimeError , so you need the try around a call to the function. 调用该函数会引发RuntimeError ,因此您需要try 调用该函数。 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. 在外部调用中处理它意味着将丢弃所有1000个递归帧,而您只需从顶层return -1 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. 在内部调用中处理它意味着您从最内部的帧返回-1 ,但是从那里到顶部的每个帧都将-1与其本地x-1相乘,然后再传递回去。 Hopefully you know which one of those you want. 希望知道您想要哪一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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