Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

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

  1. 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
    
    
    
  2. 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.")
    
    
    

Community Additions

ADD
Show:
© 2015 Microsoft