.NET中的ApplicationException是什么?

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

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

如此等等。然后我在我的代码中抛出并捕捉这些。但是今天我遇到了ApplicationException类-我应该用它来代替吗?它是用来做什么的?

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

ApplicationException应在何处与我的代码相匹配?

51359 次浏览

According to the remarks in 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.

Derive them from Exception. Also, I don't see a problem with creating new exceptions for your cases, as long as it is warranted. If you encounter a case where there is already an exception in the framework, use that, otherwise, roll your own.

In the initial design, in .NET 1.0, it was planned that the framework itself will throw SystemException and derived; while user applications - will throw ApplicationException and derived.

But later, in .NET 2.0, that was dropped.

Thus derive from Exception.

The short answer is: nowhere.

It is a relic of the past, where Microsoft intended developers to inherit all their custom exceptions from ApplicationException. Shortly after, they changed their mind and advised that custom exceptions should derive from the base Exception class. See Best Practices for Handling Exceptions on MSDN.

One of the more widely circulated reasons for this comes from an exerpt from Jeffery Richter in 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.

So there you have it. The executive summary is that ApplicationException is not harmful, just useless.