如何从称为功能中提出的异常?
如果存在文件,我的功能会引起异常:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论