【发布时间】:2012-06-26 03:30:45
【问题描述】:
我有一些看起来像这样的代码:
foreach(var obj in collection)
{
try
{
// WriteToFile returns the name of the written file
string filename = WriteToFile(obj);
SendFileToExternalAPI(filename);
}
catch ( ArbitraryType1Exception e )
{
LogError(e);
continue;
}
...
catch ( ArbitaryTypeNException e )
{
LogError(e);
continue;
}
finally
{
try
{
File.Delete(filename);
}
catch (Exception e)
{
LogError(e);
}
}
}
目标是尝试为集合中的每个对象写出一个临时文件,尝试将该文件加载到需要文件名的外部 API,然后在完成后清理临时文件。如果在将文件写入磁盘或将其加载到外部 API 时发生错误,我只想记录错误并转到下一个对象;我不能问用户该怎么做。
当您在 catch 处理程序中有 continue 语句时,我有点不确定 finally 块的时间是如何工作的。无论 try 块中是否抛出异常,这段代码是否会(尝试)删除 正确的文件?还是 catch 语句中的 continue 在 finally 块运行之前生效?
【问题讨论】:
标签: c# control-flow try-catch-finally