【发布时间】:2011-04-06 22:39:47
【问题描述】:
在不必将 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类中重新抛出异常,您将丢失之前的堆栈跟踪。 -
有没有办法保留堆栈跟踪?
-
用
throw;替换throw e; -
您可以返回
bool来判断Exception是否被处理,而不是输入ExceptionHandler。如果不是,请使用原始代码中的“throw;”。但是,总的来说,我不确定这是一个好的设计。
标签: c# exception-handling try-catch rethrow