首页 > 代码库 > 坑人的 try catch finally

坑人的 try catch finally

一直以为这样可以关闭 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, 0, bytes.Length);                                        throw new Exception();//异常不作处理                                }finally                                {                                        byte[] bytes = new UTF8Encoding().GetBytes(" finally");                                        fs.Write(bytes, 0, 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, 0, bytes.Length); throw new Exception();//异常不作处理 }finally { byte[] bytes = new UTF8Encoding().GetBytes(" finally"); fs.Write(bytes, 0, bytes.Length); if (fs != null) fs.Close(); } } catch { throw; } }

 

坑人的 try catch finally