Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

c# - What is ApplicationException for in .NET?

To throw exceptions, I usually use built-in exception classes, e.g. ArgumentNullException and NotSupportedException. However, sometimes I need to use a custom exception and in that case I write:

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

and so on. Then I throw and catch these in my code. But today I came across the ApplicationException class - should I be using that instead? What's it for?

It does seem inefficient to have lots of effectively identical Exception classes with different names (I don't usually need any individual functionality). But I dislike the idea of catching a generic ApplicationException and having to use extra code to determine what the error was.

Where should ApplicationException fit in with my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...