異常處理基於四關鍵字:try(監測區)、catch(捕獲)、finally(必執行清理)、throw(拋出)。
try {
// 可能拋異常代碼
} catch (ExceptionType1 e1) {
// 處理類型1
} catch (ExceptionType2 e2) {
// 處理類型2
} finally {
// 無論是否異常必執行(關文件、釋放鎖)
}
System.Exception
├── System.ApplicationException (用戶自定義異常基類)
└── System.SystemException (系統預定義異常基類)
├── IOException
├── IndexOutOfRangeException
├── NullReferenceException
├── DivideByZeroException
├── InvalidCastException
├── OutOfMemoryException
└── StackOverflowException
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine($"異常: {e.Message}");
} finally {
Console.WriteLine($"Result: {result}");
}
輸出:異常: Attempted to divide by zero. Result: 0
public class TempIsZeroException : ApplicationException {
public TempIsZeroException(string msg) : base(msg) {}
}
public class Temperature {
public void ShowTemp() {
if (temperature == 0) throw new TempIsZeroException("Zero Temperature");
Console.WriteLine($"Temp: {temperature}");
}
}
catch (Exception e) {
// 記錄日志
throw; // 保留原始堆疊跟蹤
// 或 throw e; // 重置堆疊跟蹤(不推薦)
}
最佳實踐:僅捕獲可處理的具體異常,避免吞沒異常;finally 保證資源釋放;自定義異常繼承 ApplicationException。