今天有点脑子不太灵光,需要帮忙验证一下我的逻辑是否正确。
传统上我会像这样进行文件 I/O 操作:
FileStream fs = null; // So it's visible in the finally block
try
{
fs = File.Open("Foo.txt", FileMode.Open);
/// Do Stuff
}
catch(IOException)
{
/// Handle Stuff
}
finally
{
if (fs != null)
fs.Close();
}
然而,这种方法并不优雅。
理想情况下,我希望使用using
块来在完成后释放文件流,但是我不确定using
和try/catch
之间的协同作用。
以下是我想要实现上述功能的方式:
try
{
using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
{
/// Do Stuff
}
}
catch(Exception)
{
/// Handle Stuff
}
然而,我担心在using块内部通过抛出异常导致过早退出可能不允许using块完成执行并清理其对象。我是多虑了吗?还是我的意图可以实现?