Custom Exceptions Sample
This solution demonstrates two more advanced exception management techniques: custom exceptions and global exception handling.
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
Click Download Sample.
The File Download message box appears.
Click Open, and on the left column of the zip folder window, click Extract all files.
The Extraction Wizard opens.
Click Next. You can change the directory that the files will be extracted to, and then click Next again.
Make sure that the Show extracted files check box is selected, and click Finish.
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
In Solution Explorer, right-click the Client project and select Set As Startup Project.
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. 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.
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 themethod will be executed instead of the default Windows Forms handler.