Elementos de tratamento de erros em tempo de execução

Erros e tratamento de erros

Quando você estiver programando um aplicativo, deverá considerar o que acontecerá quando ocorrer um erro. Um erro pode ocorrer em seu aplicativo por dois motivos. First, some condition at the time the application is running makes otherwise valid code fail. For example, if your code attempts to open a table that the user has deleted, an error occurs. Second, your code may contain improper logic that prevents it from doing what you intended. For example, an error occurs if your code attempts to divide a value by zero.

If you've implemented no error handling, then Visual Basic halts execution and displays an error message when an error occurs in your code. The user of your application is likely to be confused and frustrated when this happens. You can forestall many problems by including thorough error-handling routines in your code to handle any error that may occur.

When adding error handling to a procedure, you should consider how the procedure will route execution when an error occurs. The first step in routing execution to an error handler is to enable an error handler by including some form of the On Error statement within the procedure. The On Error statement directs execution in event of an error. If there's no On Error statement, Visual Basic simply halts execution and displays an error message when an error occurs.

When an error occurs in a procedure with an enabled error handler, Visual Basic doesn't display the normal error message. Instead it routes execution to an error handler, if one exists. When execution passes to an enabled error handler, that error handler becomes active. Within the active error handler, you can determine the type of error that occurred and address it in the manner that you choose. O Access fornece três objetos que contêm informações sobre erros ocorridos, o objeto Erro do ADO, o objeto Err do Visual Basic e o objeto Erro DAO.

Execução de roteamento quando ocorre um erro

An error handler specifies what happens within a procedure when an error occurs. For example, you may want the procedure to end if a certain error occurs, or you may want to correct the condition that caused the error and resume execution. As instruções On Error and Resume determinam como a execução prossegue no caso de um erro.

Instrução On Error

The On Error statement enables or disables an error-handling routine. If an error-handling routine is enabled, execution passes to the error-handling routine when an error occurs.

Existem três formas da instrução On Error: On Error GoTo label, On Error GoTo 0 e On Error Resume Next. A instrução On Error GoTo label ativa uma rotina de tratamento de erros a começar da linha na qual se encontra a instrução. Você deve habilitar a rotina de tratamento de erros antes da primeira linha na qual um erro poderia ocorrer. Quando a rotina de tratamento de erros está ativa e ocorre um erro, a execução passa para a linha especificada pelo argumento label.

A linha especificada pelo argumento label deve ser o início da rotina de tratamento de erros. Por exemplo, o procedimento a seguir especifica que, se ocorrer um erro, a execução passará para a linha rotulada:

Function MayCauseAnError() 
    ' Enable error handler. 
    On Error GoTo Error_MayCauseAnError 
    .            ' Include code here that may generate error. 
    . 
    . 
 
Error_MayCauseAnError: 
    .            ' Include code here to handle error. 
    . 
    . 
End Function

The On Error GoTo 0 statement disables error handling within a procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. If there's no On Error GoTo 0 statement in your code, the error handler is automatically disabled when the procedure has run completely. A instrução On Error GoTo 0 redefine as propriedades do objeto Err, tendo o mesmo efeito que o método Clear do objeto Err.

The On Error Resume Next statement ignores the line that causes an error and routes execution to the line following the line that caused the error. Execution isn't interrupted. Use a instrução On Error Resume Next se você quiser verificar as propriedades do objeto Err imediatamente após uma linha na qual você prevê que ocorrerá um erro e manipular o erro dentro do procedimento, em vez de em um manipulador de erros.

Instrução Resume

The Resume statement directs execution back to the body of the procedure from within an error-handling routine. You can include a Resume statement within an error-handling routine if you want execution to continue at a particular point in a procedure. However, a Resume statement isn't necessary; you can also end the procedure after the error-handling routine.

There are three forms of the Resume statement. The Resume or Resume 0 statement returns execution to the line at which the error occurred. A instrução Resume Next retorna a execução para a linha imediatamente seguinte à linha na qual ocorreu o erro. A instrução Resume label retorna a execução para a linha especificada pelo argumento label. O argumento label deve indicar um rótulo ou número de linha.

You typically use the Resume or Resume 0 statement when the user must make a correction. For example, if you prompt the user for the name of a table to open, and the user enters the name of a table that doesn't exist, you can prompt the user again and resume execution with the statement that caused the error.

You use the Resume Next statement when your code corrects for the error within an error handler, and you want to continue execution without rerunning the line that caused the error. Você utiliza a instrução Resume label quando deseja continuar a execução em outro ponto do procedimento, especificado pelo argumento label. Por exemplo, talvez você queira retomar a execução em uma rotina de saída, como descrito na próxima seção.

Saindo de um procedimento

When you include an error-handling routine in a procedure, you should also include an exit routine, so that the error-handling routine will run only if an error occurs. You can specify an exit routine with a line label in the same way that you specify an error-handling routine.

For example, you can add an exit routine to the example in the previous section. If an error doesn't occur, the exit routine runs after the body of the procedure. If an error occurs, then execution passes to the exit routine after the code in the error-handling routine has run. The exit routine contains an Exit statement.

Function MayCauseAnError() 
    ' Enable error handler. 
    On Error GoTo Error_MayCauseAnError 
    .            ' Include code here that may generate error. 
    . 
    . 
 
Exit_MayCauseAnError: 
    Exit Function 
 
Error_MayCauseAnError: 
    .            ' Include code to handle error. 
    . 
    . 
    ' Resume execution with exit routine to exit function. 
    Resume Exit_MayCauseAnError 
End Function

Manipulação de erros em procedimentos aninhados

Quando ocorre um erro em um procedimento aninhado que não tem uma rotina de tratamento de erros ativada, o Visual Basic procura retroativamente na lista de chamadas até encontrar uma rotina de tratamento de erros em um outro procedimento, em lugar de simplesmente parar a execução. Isso dá ao seu código a oportunidade de corrigir o erro dentro de um outro procedimento. Por exemplo, suponha que o Procedimento A chama o Procedimento B e que o Procedimento B chama o Procedimento C. Se ocorrer um erro no Procedimento C e não houver uma rotina de tratamento de erros ativada, o Visual Basic verifica se existe, no Procedimento B e depois no Procedimento A, uma rotina de tratamento de erros ativada. Se existir, a execução passa para essa rotina de tratamento de erros. Se não existir, a execução para e é exibida uma mensagem de erro.

Visual Basic also searches backward through the calls list for an enabled error handler when an error occurs within an active error handler. Você pode forçar o Visual Basic a pesquisar para trás por meio da lista de chamadas, levantando um erro dentro de um manipulador de erros ativo com o método Raise do objeto Err . This is useful for handling errors that you don't anticipate within an error handler. If an unanticipated error occurs, and you regenerate that error within the error handler, then execution passes back up the calls list to find another error handler, which may be set up to handle the error.

For example, suppose Procedure C has an enabled error handler, but the error handler doesn't correct for the error that has occurred. Once the error handler has checked for all the errors that you've anticipated, it can regenerate the original error. Execution then passes back up the calls list to the error handler in Procedure B, if one exists, providing an opportunity for this error handler to correct the error. If no error handler exists in Procedure B, or if it fails to correct for the error and regenerates it again, then execution passes to the error handler in Procedure A, assuming one exists.

Para ilustrar esse conceito de uma outra maneira, suponha que você tem um procedimento aninhado que inclui tratamento de erro para um erro de incompatibilidade de tipo, que você previu. Em algum ponto, ocorre um erro de divisão por zero, que você não previu, dentro do Procedimento C. Se você tiver incluído uma instrução para gerar novamente o erro original, a execução voltará pela lista de chamadas para uma outra rotina de tratamento de erros ativada, caso exista. Se você corrigiu um erro de divisão por zero em outro procedimento da lista de chamadas, o erro será corrigido. Se o seu código não repetir o erro, então o procedimento continuará a ser executado sem corrigir o erro de divisão por zero. Isso, por sua vez, poderá causar outros erros dentro do conjunto de procedimentos aninhados.

In summary, Visual Basic searches back up the calls list for an enabled error handler if:

  • An error occurs in a procedure that doesn't include an enabled error handler.

  • An error occurs within an active error handler. If you use the Raise method of the Err object to raise an error, you can force Visual Basic to search backward through the calls list for an enabled error handler.

Obtendo informações sobre um erro

Depois que a execução tiver passado para a rotina de tratamento de erros, seu código deverá determinar qual erro ocorreu e tratá-lo. O Visual Basic e o Access oferecem vários elementos de linguagem que você pode usar para obter informações sobre um erro específico. Each is suited to different types of errors. Since errors can occur in different parts of your application, you need to determine which to use in your code based on what errors you expect.

The language elements available for error handling include:

Objeto Err

The Err object is provided by Visual Basic. When a Visual Basic error occurs, information about that error is stored in the Err object. The Err object maintains information about only one error at a time. When a new error occurs, the Err object is updated to include information about that error instead.

Para obter informações sobre um erro específico, você pode usar as propriedades e os métodos do objeto Err :

  • A propriedade Number é a propriedade padrão do objeto Err; ela retorna o número de identificação do erro ocorrido.
  • A propriedade Description do objeto Err retorna a cadeia de caracteres descritiva associada a um erro do Visual Basic.
  • O método Clear limpa as informações atuais de erro do objeto Err.
  • The Raise method generates a specific error and populates the properties of the Err object with information about that error.

The following example shows how to use the Err object in a procedure that may cause a type mismatch error:

Function MayCauseAnError() 
    ' Declare constant to represent likely error. 
    Const conTypeMismatch As Integer = 13 
 
    On Error GoTo Error_MayCauseAnError 
        .            ' Include code here that may generate error. 
        . 
        . 
 
Exit_MayCauseAnError: 
    Exit Function 
 
Error_MayCauseAnError: 
    ' Check Err object properties. 
    If Err = conTypeMismatch Then 
        .            ' Include code to handle error. 
        . 
        . 
    Else 
        ' Regenerate original error. 
        Dim intErrNum As Integer 
        intErrNum = Err 
        Err.Clear 
        Err.Raise intErrNum 
    End If 
    ' Resume execution with exit routine to exit function. 
    Resume Exit_MayCauseAnError 
End Function

Note that in the preceding example, the Raise method is used to regenerate the original error. If an error other than a type mismatch error occurs, execution will be passed back up the calls list to another enabled error handler, if one exists.

The Err object provides you with all the information you need about Visual Basic errors. No entanto, ele não fornece informações completas sobre erros de acesso ou erros do mecanismo de banco de dados do Access. Os Objetos de Acesso e Acesso a Dados (DAO)) fornecem elementos de linguagem adicionais para ajudá-lo com esses erros.

Conjunto de erros e objeto de erro

The Error object and Errors collection are provided by ADO and DAO. The Error object represents an ADO or DAO error. A single ADO or DAO operation may cause several errors, especially if you are performing DAO ODBC operations. Each error that occurs during a particular data access operation has an associated Error object. All the Error objects associated with a particular ADO or DAO operation are stored in the Errors collection, the lowest-level error being the first object in the collection and the highest-level error being the last object in the collection.

When a ADO or DAO error occurs, the Visual Basic Err object contains the error number for the first object in the Errors collection. To determine whether additional ADO or DAO errors have occurred, check the Errors collection. The values of the ADO Number or DAO Number properties and the ADO Description or DAO Description properties of the first Error object in the Errors collection should match the values of the Number and Description properties of the Visual Basic Err object.

Método AccessError

Use o método Raise do objeto Err para gerar um erro do Visual Basic que não ocorreu de fato e determinar a cadeia de caracteres descritiva associada a esse erro. No entanto, você não pode usar o método Raise para gerar um erro do Access, um erro do ADO ou um erro DAO. Para determinar a cadeia de caracteres descritiva associada a um erro do Access, um erro do ADO ou um erro DAO que não ocorreu de fato, use o método AccessError .

Evento de erro

Use o evento Error para capturar erros que ocorrem em um formulário ou relatório do Access. For example, if a user tries to enter text in a field whose data type is Date/Time, the Error event occurs. If you add an Error event procedure to an Employees form, then try to enter a text value in the HireDate field, the Error event procedure runs.

The Error event procedure takes an integer argument, DataErr. Quando um procedimento de evento Error é executado, o argumento DataErr contém o número do erro do Access ocorrido. Checking the value of the DataErr argument within the event procedure is the only way to determine the number of the error that occurred. The Err object isn't populated with error information after the Error event occurs. Use o valor do argumento DataErr junto com o método AccessError para determinar o número do erro e sua cadeia de caracteres descritiva.

Observação

[!OBSERVAçãO] The Error statement and Error function are provided for backward compatibility only. When writing new code, use the Err and Error objects, the AccessError function, and the Error event for getting information about an error.

Sobre os colaboradores

Link fornecido peloÍcone de Membro da Comunidade da comunidade UtterAccess .

UtterAccess é o fórum principal de wiki e de ajuda do Microsoft Access.

Confira também

Suporte e comentários

Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.