How to: Filter Errors in a Catch Block in Visual Basic
Catch statements provide more than one option for filtering errors. One method for filtering is doing so by types of exception. In such cases, it is important to move from the most specific type of exception to the most general, since the Catch statements are executed in order.
A When clause can also be used to filter on a conditional expression, such as a specific error number. You can combine both approaches as well.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with General Development Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.
To filter on exception type
Insert a Catch statement for each type of exception you wish to check, going from the most specific to the most general.
Try Throw New Exception Catch ex As System.IO.IOException ' Code reacting to IOException Catch ex As System.NullReferenceException ' Code reacting to NullReferenceException Catch ex As Exception ' Code reacting to any exception End Try
To filter on a conditional expression
Use a Catch When statement to filter on a conditional expression. If the conditional expression evaluates as True, the code following the Catch block will be executed.
Try ' Code goes here. ' Check for type mismatch error. Catch ex As Exception When Err.Number = 5 ' Code reacting to exception. End Try
See Also
Tasks
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Concepts
Exception Handling for Visual Basic 6.0 Users
Choosing When to Use Structured and Unstructured Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)