沉默特定异常

Silence specific Exception

我的整个申请过程中有很多 throw new NotImplementedExceptions()。现在我想让它们静音并改为显示自定义消息对话框。

为了捕捉它们,我正在使用:

AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
     if(eventArgs.Exception is NotImplementedException) {
        return;
     }
}

但是问题是还是抛出了异常

当我在这段代码中捕捉到这种类型的异常时,我如何才能停止抛出?

听起来您想做的是在调用您尚未实现的方法时做一些比爆炸更好的事情。我认为使用 AppDomain.FirstChanceException 或相关的 UnhandledException 是不可能的。有一个 good answer here 讨论了为什么不希望简单地抑制异常。

除了引发异常之外,您还可以使用其他方法将方法标记为未实现,例如在您尚未实现某些内容时调用显示消息的助手。您可以在我自己的项目之一中使用 #if pragmas 或 ConditionalAttribute to switch to actually throwing exceptions in non-DEBUG builds, if that's desirable. It's not that uncommon to use helpers for throwing exceptions anyway (see for example ThrowHelper in the BCL, or Throw),因为避免 throws.

有一些好处

这看起来像:

public void UnImplementedMethod()
{
  // rather than "throw new NotImplementedException("some message")"
  MyHelper.NotImplemented("some message");
}

// .... 

static class MyHelper
{
  [Conditional("DEBUG")]  
  public static void NotImplemented(string msg)
  {
#if DEBUG // can use whatever configuration parameter
      MessageBox.Show("Not Implemented: "+ msg);
#else
      throw new NotImplementedException(msg);
#endif
  }
}

您可以使用泛型参数来处理具有非空 return 的未实现方法,但如果您不抛出异常,则必须决定实际 return 的内容。有了这个模式你可以为所欲为,而且仍然很容易找到没有实现的地方。