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

.NetException

.Net Problem Overview


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

.Net Solutions


Solution 1 - .Net

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.

Solution 2 - .Net

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

Solution 3 - .Net

ApplicationException considered useless is a strong, and critical, argument against ApplicationException.

Upshot: don't use it. Derive from Exception.

Solution 4 - .Net

Solution 5 - .Net

I'm used to do:

private void buttonFoo_Click()
{
    try
    {
       foo();
    } 
    catch(ApplicationException ex)
    {
      Log.UserWarning(ex);
      MessageVox.Show(ex.Message);
    }
    catch(Exception ex)
    {
       Log.CodeError(ex);
       MessageBox.Show("Internal error.");
    }
}

It allow to do the difference between:

  • C# code system error that I must repairs.
  • "Normal" user error that do not need correction from me.

I know it is not recommended to use ApplicationException, but it works great since there is very few classes that do not respect the ApplicationException pattern.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPontusView Question on Stackoverflow
Solution 1 - .NetfryguybobView Answer on Stackoverflow
Solution 2 - .NetBlorgbeardView Answer on Stackoverflow
Solution 3 - .NetKonrad RudolphView Answer on Stackoverflow
Solution 4 - .Netrp.View Answer on Stackoverflow
Solution 5 - .NetOlivier de RivoyreView Answer on Stackoverflow