c# - 沉默特定异常
问题描述
throw new NotImplementedExceptions()
在我的整个应用程序中,我有很多。现在我想让它们静音并改为显示自定义消息对话框。
为了抓住他们,我正在使用:
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
if(eventArgs.Exception is NotImplementedException) {
return;
}
}
但问题是仍然抛出异常。
当我在这段代码中捕获这种类型的异常时,如何使抛出静音?
解决方案
听起来您想要做的是在调用您尚未实现的方法时做一些比爆炸更好的事情。我不相信这是可能的使用AppDomain.FirstChanceException
或相关的UnhandledException
. 这里有一个很好的答案,它谈到了为什么简单地抑制异常是不可取的。
您可以做的是使用除了引发异常以将方法标记为未实现之外的其他方法,例如在您尚未实现某些东西时调用显示您的消息的帮助程序。如果需要,您可以使用#if
编译指示或ConditionalAttribute
切换到在非调试版本中实际抛出异常。无论如何,使用帮助程序抛出异常并不少见(例如,参见ThrowHelper
BCL 或Throw
我自己的项目之一),因为避免throw
s.
这看起来像:
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 返回的未实现方法,但如果您不抛出异常,您必须决定实际返回什么。使用这种模式,您可以做任何您想做的事情,并且仍然可以轻松找到尚未实现的地方。
推荐阅读
- javascript - 如何提取两个符号之间的值?
- c# - 如何使用转换器在 Xamarin Forms 中启用/禁用 Xaml 控件?
- google-apps-script - 根据日期删除单元格但保留格式
- scala - 如何在对行进行映射操作后保留 Spark Dataframe 的列结构
- php - 即使这些单词在字符串中不止一次,也可以从特定单词获取字符串到另一个单词
- r - 从 SAS 和内存问题调用 R
- android - Android Kotlin Retrofit + Rxjava 休息调用不返回请求的数据
- c# - 在 .NET Core 上调用 Mongo 的 C# 驱动程序时无法加载类型“System.Runtime.Remoting.Messaging.CallContext”
- c# - C#.net 无法将记录插入到 ms 访问数据库
- python - 如何只嵌入最常用的词