Export (0) Print
Expand All

Using User-Filtered Exceptions

Currently, Visual Basic and the Managed Extensions for C++ support user-filtered exceptions. User-filtered exception handlers catch and handle exceptions based on requirements you define for the exception. These handlers use the Try/Except block in the Managed Extensions for C++, or the Catch statement with the When keyword in Visual Basic.

This technique is useful when a particular exception object corresponds to multiple errors. In this case, the object typically has a property that contains the specific error code associated with the error. You can use the error code property in the expression to select only the particular error you want to handle in that Catch clause.

The following Visual Basic example illustrates the Catch/When statement.

      'Try statements.
   Catch When Err = VBErr_ClassLoadException
      'Catch statements.
End Try

The following Managed Extensions for C++ example illustrates the Try/Except statement.

int main(int argc, char **argv)
    __try {
        RunFunction(argc, argv);
    } __except(CheckForError()) {
    return 0;

The expression of the user-filtered clause is not restricted in any way. If an exception occurs during execution of the user-filtered expression, that exception overwrites the current exception. In this case, the common language runtime abandons the search for a handler for the current exception, the finally block of the try construct executes, and a search begins outside the current try construct for a handler of the new exception.

Combining the Specific Exception and the User-Filtered Clauses

A catch statement can contain both the specific exception and the user-filtered clauses. The runtime tests the specific exception first. If the specific exception succeeds, the runtime executes the user filter. The generic filter can contain a reference to the variable declared in the class filter. Note that the order of the two filter clauses cannot be reversed.

The following Visual Basic example shows the specific exception ClassLoadException in the Catch statement as well as the user-filtered clause using the When keyword.

      'Try statements.
   Catch cle As ClassLoadException When cle.IsRecoverable()
      'Catch statements.
End Try

See Also

Using the Try/Catch Block to Catch Exceptions | Using Specific Exceptions in a Catch Block | Best Practices for Handling Exceptions | Exception Handling Fundamentals

© 2015 Microsoft