Compartilhar via


Como: Manter controle quando ocorre um erro (Visual Basic)

You can use the Instrução Try...Catch...Finally (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
    

    Os três primeiros Catch blocos de lidar com as exceções que você pode prever a partir de DateAdd função. 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.

Consulte também

Tarefas

Como: Transferir controle para fora de uma estrutura de controle (Visual Basic)

Como: executar instruções dependendo de uma ou mais condições (Visual Basic)

Como: Testar vários valores de uma expressão (Visual Basic)

Conceitos

Estruturas de decisão (Visual Basic)

Estruturas de loop (Visual Basic)

Outras estruturas de controle (Visual Basic)

Estruturas de controle aninhado (Visual Basic)

Outros recursos

Fluxo de controle no Visual Basic