Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I derive custom exceptions from Exception or ApplicationException in .NET?

Tags:

.net

exception

What is best practice when creating your exception classes in a .NET solution: To derive from System.Exception or from System.ApplicationException?

like image 754
Pontus Avatar asked Sep 09 '08 19:09

Pontus


People also ask

Should I use ApplicationException?

You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception. One simple reason is that there are other exception classes in . NET derived from ApplicationException .

Should I create custom exceptions?

You should only implement a custom exception if it provides a benefit compared to Java's standard exceptions. The class name of your exception should end with Exception. If an API method specifies an exception, the exception class becomes part of the API, and you need to document it.

How do you handle custom exceptions?

Basically, Java custom exceptions are used to customize the exception according to user need. Consider the example 1 in which InvalidAgeException class extends the Exception class. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e.


2 Answers

According to Jeffery Richter in the Framework Design Guidelines book:

System.ApplicationException is a class that should not be part of the .NET framework.

It was intended to have some meaning in that you could potentially catch "all" the application exceptions, but the pattern was not followed and so it has no value.

like image 181
fryguybob Avatar answered Oct 07 '22 10:10

fryguybob


You should derive custom exceptions from System.Exception.

Even MSDN now says to ignore ApplicationException:

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.

http://msdn.microsoft.com/en-us/library/system.applicationexception.aspx

like image 31
Blorgbeard Avatar answered Oct 07 '22 10:10

Blorgbeard