What is ApplicationException for in .NET?
为了抛出异常,我通常使用内置的异常类,例如
1 2 | class SlippedOnABananaException : Exception { } class ChokedOnAnAppleException : Exception { } |
等等。然后我在代码中抛出并捕获这些。但今天我遇到了
有许多具有不同名称的有效相同异常类(我通常不需要任何单独的功能)似乎效率低下。但是我不喜欢捕获一个通用的
简短的回答是:无处可去。
这是过去的遗留问题,微软打算让开发人员从applicationexception继承他们所有的自定义异常。不久之后,他们改变了主意,建议自定义异常应该从基本异常类派生。请参阅有关处理msdn上异常的最佳实践。
其中一个更广泛传播的原因来自杰弗里里克特在框架设计指南中的一个练习:
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不是有害的,只是无用的。
根据msdn中的注释:
User applications, not the common language runtime, throw custom exceptions derived from the ApplicationException class. The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system.
If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.
从
在最初的设计中,在.NET 1.0中,计划框架本身将抛出
但后来,在.NET 2.0中,它被删除了。
由此衍生出