python2 vs. python3 raise 语句

Dom*_*ler 3 python exception raise flask python-3.x

在flask 文档中有一个钩子函数示例url_for,当找不到flask 定义的url 端点时,它允许通过调用为函数添加自定义行为。如果没有匹配的用户定义的 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)
Run Code Online (Sandbox Code Playgroud)

这段代码片段似乎是 python2 代码,并且由于该raise exc_type, exc_value, tb行而在 python3 中失败。该python2python3文件列表raise语句不同的参数。

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

Jim*_*ard 6

raise声明的文档中指定:

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

raise Exception("foo occurred").with_traceback(tracebackobj)
Run Code Online (Sandbox Code Playgroud)

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

raise exc_type(exc_value).with_traceback(tb) 
Run Code Online (Sandbox Code Playgroud)