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;
}