c# - .NET 中的 ApplicationException 是什么?

标签 c# .net exception exception-handling

为了抛出异常,我通常使用内置的异常类,例如ArgumentNullExceptionNotSupportedException。但是,有时我需要使用自定义异常,在这种情况下我会写:

class SlippedOnABananaException : Exception { }
class ChokedOnAnAppleException : Exception { }

等等。然后我在我的代码中抛出并捕获这些。但是今天我遇到了 ApplicationException 类——我应该改用它吗?它有什么用?

拥有许多名称不同但实际上完全相同的异常类似乎效率低下(我通常不需要任何单独的功能)。但我不喜欢捕获通用 ApplicationException 并且必须使用额外代码来确定错误是什么的想法。

ApplicationException 应该在哪里适合我的代码?

最佳答案

简短的回答是:无处可去。

它是过去的遗物,微软希望开发人员从 ApplicationException 继承他们所有的自定义异常。不久之后,他们改变了主意并建议自定义异常应该从基异常类派生。参见 Best Practices for Handling Exceptions在 MSDN 上。

其中一个广为流传的原因来自 Jeffery Richter 在 Framework Design Guidelines 中的一段摘录。 :

System.ApplicationException is a class that should not be part of the .NET Framework. The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException. However, a lot of exception classes didn't follow this pattern. For example, TargetInvocationException (which is thrown by the CLR) is derived from ApplicationException. So, the ApplicationException class lost all meaning. The reason to derive from this base class is to allow some code higher up the call stack to catch the base class. It was no longer possible to catch all application exceptions.

就是这样。执行摘要是 ApplicationException 不是有害,只是无用

关于c# - .NET 中的 ApplicationException 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5685923/

相关文章:

javascript - 为什么在没有单击按钮的情况下加载页面时会触发我的脚本函数?

c# - 如何防止因未设置模拟对象的期望而导致吞咽异常?

c++ - 为什么在编译时不检查 C++ 异常规范?

java - Active MQ - HelloWorld 示例异常

c# - 通过加密数据生成MAC

c# - 如何将多个数据表存储到单个数据集中

.net - AssemblyResolve 总是被提升,要求 MyAssembly.resources

c# - 检测 WebRequest 的 HTTP 代理错误

c# - Visual Studio 不再打开 Winforms 的图形编辑器

c++ - std::uniform_real_distribution - 获取所有可能的数字