什麼是異常處理,而不必把try/catch塊隨處可見的最佳做法?異常處理類
我必須創造出一種專門用於接收和處理異常一類的想法,但如果我想知道一個良好的設計理念。這樣的類將收到異常,然後再決定如何處理它根據其類型或錯誤代碼做,甚至可以解析爲特定的堆棧跟蹤信息,等
這裏是背後的基本思想和實現:
public class ExceptionHandler
{
public static void Handle(Exception e)
{
if (e.GetBaseException().GetType() == typeof(ArgumentException))
{
Console.WriteLine("You caught an ArgumentException.");
}
else
{
Console.WriteLine("You did not catch an exception.");
throw e; // re-throwing is the default behavior
}
}
}
public static class ExceptionThrower
{
public static void TriggerException(bool isTrigger)
{
if (isTrigger)
throw new ArgumentException("You threw an exception.");
else
Console.WriteLine("You did not throw an exception.");
}
}
class Program
{
static void Main(string[] args)
{
try
{
ExceptionThrower.TriggerException(true);
}
catch(Exception e)
{
ExceptionHandler.Handle(e);
}
Console.ReadLine();
}
}
我認爲這將是一個有趣的嘗試,因爲理論上你只需要在main()方法調用周圍需要一個或很少的try/catch塊,並讓異常類處理其他所有事情,包括重新拋出,處理,記錄,不管。
的思考?
通過在你的'ExceptionHandler'類中重新拋出異常,你將失去先前的堆棧跟蹤。 – 2011-04-06 22:45:56
有沒有辦法保存堆棧跟蹤? – 2011-04-06 22:52:18
用'throw;'替換'throw e;'' – 2011-04-06 22:53:03