How to: Test Code with a Try…Catch Block in Visual Basic
A Catch statement can be used within a Try block in order to catch and respond to a specific exception or multiple exceptions. If an exception occurs during the execution of any of the code within the Try section, the Visual Basic compiler examines each Catch statement within the block until it finds one whose condition matches that exception. If none is found, an error is produced.
To catch a specific exception
Use a Try block to test the block of code, enclosing it within Try and End Try, as in the following example, which copies the file MyLog to the same directory and renames it BackupLog.
Try My.Computer.FileSystem.CopyFile("MyLog", "BackupLog") Catch ex As System.IO.IOException MsgBox("An error occurred") End Try
Within the Try block, supply Catch statements aimed at specific types of errors, going from the most specific to the least specific. Here, the Catch statement first catches any IOException exceptions before looking for general exceptions.
Catch ex As System.IO.FileNotFoundException MsgBox("No such file in this directory.") Catch ex As System.Exception MsgBox("An unspecified error occurred.")