This documentation is archived and is not being maintained.

Custom Exceptions Sample

Visual Studio 2008

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

To get samples and instructions for installing them

  • Do one or more of the following:

    • On the Help menu, click Samples.

      The Readme displays information about samples.

    • Visit the Visual Studio 2008 Samples Web site. The most recent versions of samples are available there.

    • Locate samples on the computer on which Visual Studio is installed. By default, samples and a Readme file are installed in drive:\Program Files\Microsoft Visual Studio 9.0\Samples\lcid. For Express editions of Visual Studio, all samples are located online.

For more information, see Visual Studio Samples.

Security noteSecurity Note:

This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties.

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.