Custom Exceptions Sample

To get samples and instructions for installing them, see the following:

  • Click Samples on the Visual Studio Help menu.

    For more information, see Locating Sample Files.

  • The most recent versions and the complete list of samples are available on the Visual Studio 2008 Samples Web site.

  • You can also locate samples on your computer's hard disk. By default, samples and a Readme file are copied to a folder under \Program Files\Visual Studio 9\Samples\. For Visual Studio Express Editions, all samples are located on the Internet.

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.

Demonstrates

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.