坑人的 try catch finally

时间:2021-07-02 08:21:32
一直以为这样可以关闭 fs, 其实不行

static void Main(string[] args)
{
FileStream fs = null;
try
{
fs = new FileStream(@"d:\data.txt", FileMode.Create);
byte[] bytes = new UTF8Encoding().GetBytes("try");
fs.Write(bytes, , bytes.Length);
throw new Exception();//异常不作处理
}finally
{
byte[] bytes = new UTF8Encoding().GetBytes(" finally");
fs.Write(bytes, , bytes.Length);
if (fs != null)
fs.Close();
}
}

要这样才能有效关闭 fs: static void Main(string[] args)
{
try
{
FileStream fs = null;
try
{
fs = new FileStream(@"d:\data.txt", FileMode.Create);
byte[] bytes = new UTF8Encoding().GetBytes("try");
fs.Write(bytes, , bytes.Length);
throw new Exception();//异常不作处理
}finally
{
byte[] bytes = new UTF8Encoding().GetBytes(" finally");
fs.Write(bytes, , bytes.Length);
if (fs != null)
fs.Close();
}
}
catch
{
throw;
}
}