python2与python3 raise语句

时间:2017-07-30 21:26:27

标签: python python-3.x exception flask raise

在flask文档中有一个钩子函数的例子,当没有找到瓶子定义的url端点时,它允许通过被调用为url_for函数添加自定义行为。如果没有匹配的用户定义的url端点,程序员可以添加自定义端点或重新引发异常(使用原始上下文)。

def external_url_handler(error, endpoint, values):
    "Looks up an external URL when `url_for` cannot build a URL."
    # This is an example of hooking the build_error_handler.
    # Here, lookup_url is some utility function you've built
    # which looks up the endpoint in some external URL registry.
    url = lookup_url(endpoint, **values)
    if url is None:
        # External lookup did not have a URL.
        # Re-raise the BuildError, in context of original traceback.
        exc_type, exc_value, tb = sys.exc_info()
        if exc_value is error:
            raise exc_type, exc_value, tb
        else:
            raise error
    # url_for will use this result, instead of raising BuildError.
    return url

app.url_build_error_handlers.append(external_url_handler)

此代码段似乎是python2代码,因为raise exc_type, exc_value, tb行而导致python3失败。 python2python3文档列出了raise语句的不同参数。

将此代码段转换为python3的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

这在the raise statement的文档中指定:

  

您可以使用with_traceback()异常方法(返回相同的异常实例,并将其traceback设置为其参数),在一个步骤中创建异常并设置您自己的回溯,如下所示:

raise Exception("foo occurred").with_traceback(tracebackobj)

所以,在你的情况下,那将是:

raise exc_type(exc_value).with_traceback(tb)