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
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. 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 (Visual Basic)
Troubleshooting Exception Handling (Visual Basic)
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling (Visual Basic)