Common Language Runtime (CLR) 將例外處理標準化為跨語言機制,C# 提供豐富的例外處理功能。本章涵蓋整數溢位檢查、標準例外處理區塊、自訂例外類別與最佳實務。
C# 預設不檢查整數溢位。例如計算 2000! 會靜默回傳 0 而不拋出例外。
csc /checked+ program.cs,啟用整個組件的溢位檢查。checked { ... } 包裹需檢查的程式碼,unchecked { ... } 則在啟用全域檢查時局部關閉。
// 局部啟用檢查
checked {
nFactorial *= nCurDig; // 溢位時拋出 OverflowException
}
// 局部關閉檢查(即使全域啟用)
unchecked {
nFactorial *= nCurDig; // 靜默截斷
}
溢位時拋出 System.OverflowException。
try {
// 可能拋出例外的程式碼
checked { for (...) nFactorial *= nCurDig; }
}
catch (OverflowException oe) {
Console.WriteLine("溢位: {0}", oe.Message);
return;
}
catch (Exception e) {
// 捕獲其他所有例外
LogError(e);
}
可捕獲特定例外型別,或使用 catch (Exception e) 捕獲所有。catch 區塊不可使用 ref/out 修飾例外參數。
finally 區塊在 try 區塊結束時總是執行(無論是否發生例外、是否有 return),適用於資源釋放、關閉連線等清理工作。
bool success = false;
try {
// 關鍵操作
success = true;
}
finally {
if (!success) Console.WriteLine("操作失敗");
// 清理資源
CloseHandles();
}
結合捕獲與清理,finally 在 catch 之後、控制權離開前執行。
繼承 System.ApplicationException 或 System.Exception,建議提供三個建構函式:
public class BusinessRuleException : ApplicationException {
public BusinessRuleException() { }
public BusinessRuleException(string message) : base(message) { }
public BusinessRuleException(string message, Exception inner) : base(message, inner) { }
}
拋出時:throw new BusinessRuleException("餘額不足", originalException);
finally 確保非受管理資源釋放。catch 區塊中拋出新例外而不包裝原始例外(丟失堆疊追蹤)。C# 例外處理提供型別安全、跨語言一致的錯誤處理機制。善用 checked/unchecked 控制溢位行為,結合 try-catch-finally 確保資源正確釋放,並設計領域特定的自訂例外,能構建健壯且可維護的應用程式。