C#抛出异常并使用相同的方法捕获它为什么不好?

时间:2018-11-21 12:08:09

标签: c# .net code-structure

讨论一种实现:

// 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(以相同的方法抛出并捕获)来安全地执行某些操作并汇总不同类型的类似异常,这可能是一个糟糕的设计的原因?

1 个答案:

答案 0 :(得分:1)

不是扔掉

 throw new WrapedException("MyNewMessage", ex);

那是错误的,但是捕获了 all 所有异常

 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);
     }
   }