Share via


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

See Also

Tasks

How to: Clean up Resources with a Try…Finally Block in Visual Basic

How to: Filter Errors in a Catch Block in Visual Basic

How to: Check an Exception's Inner Exception

Troubleshooting Exception Handling

Concepts

Choosing When to Use Structured and Unstructured Exception Handling

Reference

Try...Catch...Finally Statement (Visual Basic)

Other Resources

Exception Handling Tasks