Walkthrough: Replacing One Exception with Another

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

This walkthrough demonstrates the steps to replace one exception with another before propagating the exception. Figure 1 illustrates the process.

Ff648218.e1143990-00bb-4491-ac10-f3f89ffa0b2c(en-us,PandP.10).png

Figure 1
Replacing one exception with another

The QuickStart executable calls a method in the business layer assembly, and an exception occurs. The Exception Handling Application Block uses the specified policy—Replace Policy—to handle the exception.

The Replace Policy specifies that exceptions of type SecurityException will be replaced with exceptions of type ApplicationException. The policy is configured so that exceptions of type SecurityException have a PostHandlingAction of ThrowNewException. This causes the Exception Handling Application Block to throw the new ApplicationException after the last handler in the chain executes.

The QuickStart executable catches this exception and calls ProcessUnhandledException. This routine calls HandleException and passes the policy named Global Policy. This policy is configured to run a custom exception handler that displays a dialog box that contains the exception message.

To reproduce this scenario

  1. Create a new blank solution in Visual Studio.
  2. Add a Windows-based application project named ExceptionHandlingBasicQuickStart to the solution.
  3. Add a class library project named ExceptionHandlingQuickStart.BusinessLayer to the solution.
  4. Rename the class in ExceptionHandlingQuickStart.BusinessLayer to AppService.
  5. Import the System.Security class and the System.Security.Principal namespace.
  6. Add the ProcessC and ProcessWithReplace methods to the AppService class. These methods are included in the QuickStart source code.
  7. Use the configuration tools to create a new application configuration file.
  8. Use the configuration tools to add the Exception Handling Application Block to the application.
  9. Add a new exception policy named Replace Policy.
  10. Add the exception type SecurityException to Replace Policy.
  11. Configure the SecurityException exception type to have a PostHandlingAction of ThrowNewException.
  12. Add a replace handler for the SecurityException exception type.
  13. Specify a new System.ApplicationException exception type for the replace handler to use for replacing the SecurityException.
  14. Enter the new message for the new exception.