c# - 异常抛出 : encapsulate them or not?

标签 c# .net encapsulation

有一次我读到 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/

相关文章:

c# - 在 C# 中使用分隔符连接字节数组

c# - 在自定义 UserControl 上强制使用透明背景

c# - 从 Windows 服务创建交互式提升进程并显示给登录用户

c# - 如何在我的项目中实现 WCF?

C# sql 创建一个连接并为每个查询打开和关闭

java异常保留封装示例

c++ - 作为成员或非成员函数的算法?

java - 关于在 Java 中正确使用封装的建议

.net - 在 .NET 2.0+ 中使用集合相对于 List(Of T) 有什么优势

c# - Visual Studio 2012 生成后事件 - 错误代码 255