Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual Basic
 How to: Test Code with a Try…Catch ...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
Visual Basic Application Development
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.

    Visual Basic
    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.

    Visual Basic
    Catch ex As System.IO.FileNotFoundException
        MsgBox("No such file in this directory.")
    Catch ex As System.Exception
        MsgBox("An unspecified error occurred.")
    
    
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker