处理异常而不必到处放置 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 块,并让异常类处理其他所有事情,包括重新抛出、处理、日志记录等。
想法?