首页 > 其他 > 详细

坑人的 try catch finally

时间:2014-10-25 17:02:35      阅读:223      评论:0      收藏:0      [点我收藏+]
一直以为这样可以关闭 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

原文:http://www.cnblogs.com/yipeng-yu/p/4050219.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!