c# try-finally有什么用

 finally 代码块中的代码是 try-catch 结构执行完后无论有无异常发生都会执行的。finally 代码块中的代码是 try-catch 结构执行完后无论有无异常发生都会执行的。finally 代码块中的代码是 try-catch 结构执行完后无论有无异常发生都会执行的。



重要的事情说三遍。重点要强调的是,finally 的执行条件只有这一个。

为什么要这么强调。是因为你很可能在 try-catch 里直接 return 啊 break 啊 continue 啥的,导致跳出 try-catch 结构。你可能会想当然的认为既然我 return 了直接返回结果 finally 里的代码就不会执行。这是错误的!因为 finally 执行条件只是【try-catch 结构执行完】,即使 try-catch 里 return 了,依然还是会先执行 finally 里的代码,然后才会真的 return。


而你要是不用 finally,直接把最后要统一执行的代码放在 try-catch 外面,那 try-catch 一 return,你的代码就不会被执行了。

所以 finally 最常用的地方是在里面释放对象占用的资源的。

例子:
        private bool DownloadPicture(string picUrl, string savePath, int timeOut)
        {
            bool value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1) request.Timeout = timeOut;
                response = request.GetResponse();
                stream = response.GetResponseStream();
                if (!response.ContentType.ToLower().StartsWith("text/"))
                    value = SaveBinaryFile(response, savePath);
            }
            finally
            {
                if (stream != null) stream.Close();
                if (response != null) response.Close();
            }
            return value;

        } 

posted @ 2018-03-06 17:11  程序猿kid  阅读(1925)  评论(0编辑  收藏  举报