首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 例外處理機制深度解析:checked/unchecked、try-catch-finally 與自訂例外

     編輯:關於C語言

前言

Common Language Runtime (CLR) 將例外處理標準化為跨語言機制,C# 提供豐富的例外處理功能。本章涵蓋整數溢位檢查、標準例外處理區塊、自訂例外類別與最佳實務。

整數溢位檢查:checked 與 unchecked

預設行為

C# 預設不檢查整數溢位。例如計算 2000! 會靜默回傳 0 而不拋出例外。

啟用溢位檢查的兩種方式

  1. 編譯器選項:csc /checked+ program.cs,啟用整個組件的溢位檢查。
  2. 陳述式區塊:使用 checked { ... } 包裹需檢查的程式碼,unchecked { ... } 則在啟用全域檢查時局部關閉。

// 局部啟用檢查
checked {
    nFactorial *= nCurDig; // 溢位時拋出 OverflowException
}
// 局部關閉檢查(即使全域啟用)
unchecked {
    nFactorial *= nCurDig; // 靜默截斷
}

溢位時拋出 System.OverflowException。

標準例外處理架構

try-catch:捕獲與處理


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 修飾例外參數。

try-finally:確保清理程式碼執行

finally 區塊在 try 區塊結束時總是執行(無論是否發生例外、是否有 return),適用於資源釋放、關閉連線等清理工作。


bool success = false;
try {
    // 關鍵操作
    success = true;
}
finally {
    if (!success) Console.WriteLine("操作失敗");
    // 清理資源
    CloseHandles();
}

try-catch-finally:完整處理模式

結合捕獲與清理,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 確保資源正確釋放,並設計領域特定的自訂例外,能構建健壯且可維護的應用程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved