Bagikan melalui


How to: Retain Control When an Error Occurs

You can use the Try...Catch...Finally Statement (Visual Basic) construction for structured exception handling. This allows you to run a particular block of statements if a specified exception occurs while your code is running. When this happens, the code is said to throw the exception, and you catch it with the appropriate Catch statement.

To run a set of statements if your code causes an exception

  • Use the Try...Catch...Finally construction to enclose the code that might cause an exception. Then, specify the code to run if an exception occurs, and optionally provide a set of statements to run before control leaves the Try...Catch...Finally construction.

    The following example attempts to calculate the date and time exactly 100 years after the value provided in the Object variable givenDate.

    Dim givenDate As Object
    Dim nextCentury As Date
    Try
        nextCentury = Microsoft.VisualBasic.DateAdd("yyyy", 100, givenDate)
        Catch thisExcep As System.ArgumentOutOfRangeException
        ' The resulting date/time is later than December 31, 9999.
        Catch thisExcep As System.ArgumentException
        ' At least one argument has an invalid value.
        Catch thisExcep As System.InvalidCastException
        ' The value in givenDate cannot be interpreted as a date/time.
        Catch
        ' An unforeseen exception has occurred.
        Finally
        ' This block is always run before leaving the Try structure.
    End Try
    

    The first three Catch blocks handle the exceptions that you can anticipate from the DateAdd Function (Visual Basic). You can deal with any unexpected exception in the last Catch block.

    No matter what happens, the Finally block is always the last code to be run before leaving the Try...Catch...Finally construction. If you create or open resources such as objects or database connections in a Try or Catch block, you can use the Finally block to close them and dispose of them, if appropriate.

    If the exception variable thisExcep does not appear in a declaration statement such as Dim, the Catch statement with the As clause serves as a declaration.

See Also

Tasks

How to: Transfer Control Out of a Control Structure

How to: Run Statements Depending on One or More Conditions

How to: Test for Several Values of an Expression

Concepts

Decision Structures

Loop Structures

Other Control Structures

Nested Control Structures

Other Resources

Control Flow in Visual Basic