0

我有一些这样的代码:

with open(output_path, 'w') as output_file:
    #create and write output file

运行此程序后,即使某处出现错误,文件也已创建并处于不完整状态。

我想要它,如果在 with 块中引发(且未处理)异常,则删除该文件。最好的方法是什么?

我的理解是,如果我尝试用 (try ...)finally语句来做,即使没有异常也会发生,而如果我把它放在except语句之后,异常不会继续冒泡,这是我想要它做什么。(我不想处理异常,只需在代码停止运行之前删除文件即可。)

4

1 回答 1

0

您可以简单地在您的 except 块中调用 raise,它会重新引发异常以允许异常冒泡。请参阅 python 文档的相关部分

对于您的示例,您可以编写类似于以下内容的内容:

try:
    with open(output_path, 'w') as output_file:
        # Create and write output file.
except:
    # Delete the file.
    # Re-raise the exception with all relevant information (message, stacktrace, etc).
    raise
于 2014-10-27T04:58:31.347 回答