首页 > 解决方案 > 沉默特定异常

问题描述

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

为了抓住他们,我正在使用:

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

但问题是仍然抛出异常。

当我在这段代码中捕获这种类型的异常时,如何使抛出静音?

标签: c#exceptionappdomain

解决方案


听起来您想要做的是在调用您尚未实现的方法时做一些比爆炸更好的事情。我不相信这是可能的使用AppDomain.FirstChanceException或相关的UnhandledException. 这里有一个很好的答案,它谈到了为什么简单地抑制异常是不可取的。

您可以做的是使用除了引发异常以将方法标记为未实现之外的其他方法,例如在您尚未实现某些东西时调用显示您的消息的帮助程序。如果需要,您可以使用#if编译指示或ConditionalAttribute切换到在非调试版本中实际抛出异常。无论如何,使用帮助程序抛出异常并不少见(例如,参见ThrowHelperBCL 或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
  }
}

您可以使用泛型参数来处理具有非 void 返回的未实现方法,但如果您不抛出异常,您必须决定实际返回什么。使用这种模式,您可以做任何您想做的事情,并且仍然可以轻松找到尚未实现的地方。


推荐阅读