有一次我读到 MSDN article这鼓励了以下编程范式(它不是 100% 正确的......见编辑):
public class MyClass
{
public void Method1()
{
NewCustomException();
}
public void Method2()
{
NewCustomException();
}
void NewCustomException()
{
throw new CustomException("Exception message");
}
}
您认为这种范式有意义吗?将异常消息存储在 static const
字段中然后将其传递给异常的构造函数,而不是封装整个异常抛出是否足够?
编辑:
Use exception builder methods. It is common for a class to throw the same exception from different places in its implementation. To avoid excessive code, use helper methods that create the exception and return it.
我刚注意到(见引文),这篇文章告诉我们返回一个异常:
public class MyClass
{
public void Method1()
{
throw NewCustomException();
}
public void Method2()
{
throw NewCustomException();
}
CustomException NewCustomException()
{
return new CustomException("Exception message");
}
}
你怎么看这件事?
最佳答案
我的理解是,传递一个异常实例是一种失礼,如果没有其他原因,只是你丢失了与异常相关的堆栈跟踪。调用另一种方法会更改堆栈跟踪,从而使其实际上变得无用。我建议至少从异常中获取堆栈跟踪并将其作为参数传递给某个助手,如果那是你要走的路的话。
关于c# - 异常抛出 : encapsulate them or not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2967909/