class Program
{
static void Main(string[] args)
{
try
{
throw new NotImplementedException("Oh dear");
}
catch (Exception ex)
{
throw NewException("Whoops", ex);
}
}
// This function is the salient bit here
public static Exception NewException(String message, Exception innerException)
{
return Activator.CreateInstance(innerException.GetType(), message, innerException) as Exception;
}
}
重要的一点是,该函数创建了与“innerException”相同类型的异常。
我想...“哦...发生了异常。我实际上无法在这里处理它,但我可以添加一些额外的信息并重新抛出。也许另一个调用链更高的处理程序可以处理它。”
例如,某种SQL错误。我可能无法在调用点处处理异常,但可能希望添加一些额外的“上下文”信息,例如“我正在调用此函数,并传递那个参数”。
似乎将最初引发的异常类型作为回传调用链异常的类型,而不是“Exception”或“ApplicationException”,可能是有用的。当然,我可能错了。这可能是一个非常有用的事情...但小声音建议不要这样做。
----- 编辑 -----
为了辩论起见,请考虑以下两个函数的效果(使用上面的代码):
这...经常出现的情况:
static int SalesTotal(int customerNumber)
{
try
{
throw new DivideByZeroException(); // something you didn't expect
}
catch (Exception ex)
{
throw new ApplicationException("Unable to calculate sales for customer " + customerNumber, ex);
}
}
相比之下...
static int SalesTotal(int customerNumber)
{
try
{
throw new DivideByZeroException(); // something you didn't expect
}
catch (Exception ex)
{
throw NewException("Unable to calculate sales for customer " + customerNumber, ex);
}
}
(String, Exception)
构造函数。 - Heinzi