首页 > 解决方案 > C# 抛出异常并以相同的方法捕获它为什么不好?

问题描述

对一种实现进行一些讨论:

// Pseudocode
accessor type GetValue() 
{
    try
    {
        do some action with possible throw exception1
        do some action with possible throw exception2

        return value;
    }
    catch (Exception ex)
    {
        value = default;
        throw Wraped in Meaningfull Exception ex

    }
}

有人可以解释为什么使用它可能是一个糟糕的设计try-catch像这样(以相同的方法抛出和捕获)来安全地执行一些操作并聚合不同类型的类似异常吗?

标签: c#.netcode-structure

解决方案


这不是重新抛出

 throw new WrapedException("MyNewMessage", ex);

这是错误的,但捕获所有异常

 catch (Exception ex) {
   ...
 }

是一个糟糕的设计:它掩盖了潜在的危险行为。让我们看看为什么。假设我们这样使用GetValue()

   try {
     someValue = GetValue();
   }
   catch (WrapedException) {  
     // We failed to obtain someValue;
     // The reason - WrapedException - is innocent
     // Let's use default value then

     someValue = defaultSomeValue;
   }

而实际图片是

   public GetValue() {
     try {
       do some action with possible throw exception1

       // Catastrophy here: AccessViolationException! System is in ruins!
       do some action with possible throw exception2

       return value;
     }
     catch (Exception ex) { // AccessViolationException will be caught...
       // ...and the disaster will have been masked as being just WrapedException
       throw new WrapedException("MyNewMessage", ex);
     }
   }

如果您只捕获预期的异常类型,您的设计是可以的:

   public GetValue() {
     try {
       do some action with possible throw exception1
       do some action with possible throw exception2

       return value;
     }
     catch (FileNotFound ex) {
       // File not found, nothing special in the context of the routine
       throw new WrapedException("File not found and we can't load the CCalue", ex);
     }
   }

推荐阅读