如何从称为功能中提出的异常?

发布于 2025-02-03 20:12:58 字数 987 浏览 3 评论 0原文

如果存在文件,我的功能会引起异常:

def save_template(rendered_template, target_path, file_name):
    fl = os.path.join(target_path, file_name)
    if os.path.exists(fl):
        raise Exception
    with open(fl, "w") as f:
        f.write(rendered_template)

我有另一个调用save_template的函数。

def build_controller():
    # ... some other code
    try:
        save_template(rendered, path, file_name)

    except:
        echo(f"{path}/{file_name} already exists. Doing nothing.", "yellow")

try-except build_controller中的语句没有捕获异常。从save_template提出了例外。

我还对此进行了测试:

def save_template(rendered_template, target_path, file_name):
    raise Exception

和以下:

def save_template(rendered_template, target_path, file_name):
    return Exception

结果相同。

如何从save_template中捕获错误并在有错误时运行我的echo命令?

I have a function that raises an exception if a file exists:

def save_template(rendered_template, target_path, file_name):
    fl = os.path.join(target_path, file_name)
    if os.path.exists(fl):
        raise Exception
    with open(fl, "w") as f:
        f.write(rendered_template)

I have another function that calls save_template.

def build_controller():
    # ... some other code
    try:
        save_template(rendered, path, file_name)

    except:
        echo(f"{path}/{file_name} already exists. Doing nothing.", "yellow")

The try-except statement in build_controller is not catching the exception. The exception is being raised from save_template.

I've also tested with this:

def save_template(rendered_template, target_path, file_name):
    raise Exception

And this:

def save_template(rendered_template, target_path, file_name):
    return Exception

With the same result.

How do I catch errors from save_template and run my echo command if there's an error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文