使用 try/catch 處理異常
try-catch 塊的用途是捕捉和處理工作代碼所生成的異常。 有些異常可以在 catch 塊中處理,解決問(wèn)題后不會(huì)再次引發(fā)異常;但更多情況下,您唯一能做的是確保引發(fā)適當(dāng)?shù)漠惓!?br /> 示例
在此示例中,IndexOutOfRangeException 不是最適當(dāng)?shù)漠惓#簩?duì)本方法而言 ArgumentOutOfRangeException 更恰當(dāng)些,因?yàn)殄e(cuò)誤是由調(diào)用方傳入的 index 參數(shù)導(dǎo)致的。
class TestTryCatch{ static int GetInt(int[] array, int index) { try { return array[index]; } catch (System.IndexOutOfRangeException e) // CS0168 { System.Console.WriteLine(e.Message); // Set IndexOutOfRangeException to the new exception's InnerException. throw new System.ArgumentOutOfRangeException("index parameter is out of range.", e); } }}
注釋
導(dǎo)致異常的代碼被括在 try 塊中。 在其后面緊接著添加一個(gè) catch 語(yǔ)句,以便在 IndexOutOfRangeException 發(fā)生時(shí)對(duì)其進(jìn)行處理。 catch 塊處理 IndexOutOfRangeException,并引發(fā)更適當(dāng)?shù)?ArgumentOutOfRangeException 異常。 為給調(diào)用方提供盡可能多的信息,應(yīng)考慮將原始異常指定為新異常的 InnerException。 因?yàn)?InnerException 屬性是只讀,所以必須在新異常的構(gòu)造函數(shù)中為其賦值。
使用 finally 執(zhí)行清理代碼
finally 語(yǔ)句的目的是確保即使在引發(fā)異常的情況下也能立即進(jìn)行必要的對(duì)象(通常是保存外部資源的對(duì)象)清理。此類清理功能的一個(gè)示例是在使用后立即對(duì) FileStream 調(diào)用 Close,而不是等待公共語(yǔ)言運(yùn)行時(shí)對(duì)該對(duì)象進(jìn)行垃圾回收,如下所示:
static void CodeWithoutCleanup(){ System.IO.FileStream file = null; System.IO.FileInfo fileInfo = new System.IO.FileInfo("C://file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); file.Close();} 為了將上面的代碼轉(zhuǎn)換為 try-catch-finally 語(yǔ)句,需要將清理代碼與工作代碼分開(kāi),如下所示。
static void CodeWithCleanup(){ System.IO.FileStream file = null; System.IO.FileInfo fileInfo = null; try { fileInfo = new System.IO.FileInfo("C://file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); } catch(System.UnauthorizedAccessException e) { System.Console.WriteLine(e.Message); } finally { if (file != null) { file.Close(); } }} 因?yàn)樵?OpenWrite() 調(diào)用前,try 塊內(nèi)隨時(shí)都有可能發(fā)生異常,OpenWrite() 調(diào)用本身也有可能失敗,所以我們無(wú)法保證該文件在我們嘗試關(guān)閉它時(shí)處于打開(kāi)狀態(tài)。 finally 塊添加了一項(xiàng)檢查,以確保在調(diào)用 Close 方法前,F(xiàn)ileStream 對(duì)象不為 null。如果沒(méi)有 null 檢查,finally 塊可能引發(fā)自身的 NullReferenceException,但是應(yīng)當(dāng)盡可能避免在 finally 塊中引發(fā)異常。
在 finally 塊中關(guān)閉數(shù)據(jù)庫(kù)連接是另一個(gè)不錯(cuò)的選擇。因?yàn)橛袝r(shí)候數(shù)據(jù)庫(kù)服務(wù)器允許的連接數(shù)是有限的,所以應(yīng)盡快關(guān)閉數(shù)據(jù)庫(kù)連接。在由于引發(fā)了異常而無(wú)法關(guān)閉連接的情況下,使用 finally 塊也是比等待垃圾回收更好的一種選擇。



















