throw new ExceptionType();:拋出新異常throw;:在 catch 區塊中重新拋出原異常(保留堆疊追蹤)throw ex;:重新拋出但重設堆疊追蹤(除錯大忌)using System;
namespace ClsUserException
{
// 慣例:類別名以 Exception 結尾
public class UserEmployeeException : Exception
{
public string ErrorInfo { get; }
// 無參數建構函式
public UserEmployeeException() : base() { }
// 帶訊息建構函式
public UserEmployeeException(string message) : base(message)
{
ErrorInfo = message;
}
// 帶訊息與內部異常建構函式(支援異常鏈)
public UserEmployeeException(string message, Exception inner) : base(message, inner)
{
ErrorInfo = message;
}
// 序列化建構函式(跨 AppDomain/遠端呼叫需求)
protected UserEmployeeException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
public static void Main()
{
try
{
throw new UserEmployeeException("error Info of use");
}
catch (UserEmployeeException ex)
{
Console.WriteLine("輸出結果為:");
Console.WriteLine(ex.Message);
Console.Read();
}
}
ValidationException、InsufficientFundsException。try { /* ... */ }
catch (UserEmployeeException ex) when (ex.ErrorCode == 401)
{
// 僅處理特定錯誤代碼
}
catch (UserEmployeeException ex)
{
// 處理其他同類異常
}
throw 是領域模型表達業務規則違反的關鍵機制。善用自訂異常讓錯誤語意化、可程式化處理,配合 when 過濾器實現精準捕獲。記住:throw; 保留堆疊,throw ex; 破壞堆疊——除非你很清楚在做什麼,永遠用 throw;。