Exception classes

Overview

  • All .NET exceptions derive from the System.SystemException class.
  • All custom exceptions derive from the System.Exception class.
    • For most applications, 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. (From MSDN)
  • The try/catch structure will use the first catch which applies. Order catches from most specific to most general in the code.
  • Finally will always be executed, whether an exception got thrown or not.
  • A try/catch/finally construct has multiple separated scopes, demonstrated below.

Good practice

  • End custom exception classes with 'Exception'.
  • Implement the three recommended common constructors, as shown in the example.

Examples

Scopes

int a;
try
{
    int b;
    // a and b are accessible.
}
catch (Exception e)
{
    int c;
    // a and c are accessible.
}
finally
{
    int d;
    // a and d are accessible.
}

Constructors

using System;
public class EmployeeListNotFoundException : Exception
{
    public EmployeeListNotFoundException()
    {
    }
 
    public EmployeeListNotFoundException(string message)
        : base(message)
    {
    }
 
    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}