This documentation is archived and is not being maintained.

Custom Exceptions Sample 

Download sample

This solution demonstrates two more advanced exception management techniques: custom exceptions and global exception handling.

Security noteSecurity Note

This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.

To open the sample file in Solution Explorer

  1. Click Download Sample.

    The File Download message box appears.

  2. Click Open, and on the left column of the zip folder window, click Extract all files.

    The Extraction Wizard opens.

  3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.

  4. Make sure that the Show extracted files check box is selected, and click Finish.

  5. Double-click the sample's .sln file.

    The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location is not trusted. Click OK to continue.

To run this sample

  1. In Solution Explorer, right-click the Client project and select Set As Startup Project.

  2. Press CTRL+F5. The program is best run outside the debugger to see the effects of a global exception handler.


This sample contains two projects: a Windows Forms client and a class library.

Class Library (Server)

The class library defines the Customer and a set of custom exception classes that are used to expose application-defined errors. The exception classes are related by an inheritance hierarchy. The base class is CRMSystemException, which inherits from ApplicationException. CustomerException and EmployeeException inherit from CRMSystemException. There are two more exceptions which inherit from CustomerException: CustomerNotFoundException and CustomerNotDeletedException. Each class exposes different levels of information and functionality.

Client Code

The client application has a reference to the class library. Two command buttons execute methods against the Customer class and catch the custom exceptions. A third command button causes an unhandled exception. In addition, there is a check box labeled "Turn on Global Exception Trap" that enables a global exception trap. When enabled, the code defined in the OnThreadException method will be executed instead of the default Windows Forms handler.

See Also