As you have already mentioned all, there is no clause TRY..CATCH
, at least as we can know it from other languages. What does exist in all versions of Visual Basic up to v6, in VbScript and Vba, is an error handler, with the clause ON Error
that with a little work allows to do several things and in this I want to deepen my response , let's see:
-
On Error GoTo #línea
: Establishes that from the next instruction, until the end of the routine or function or until the next ON Error
any error captured will cause the execution to continue in the indicated line. The line does not have to be a number like the language Basic
did, but a etiqueta
, for example ErroHandler:
(note the :
). This line that establishes our error handler must be within the routine or function: the GOTO
has no way to "exit" the routine from which it is invoked.
-
On Error Resume Next
: As the name implies, it captures the error and makes the execution continue with the next instruction. For practical purposes, no error is displayed and the execution continues.
-
On Error goto 0
: A somewhat strange way to indicate that we want to remove the current error handler.
As a demonstration of this:
Sub Test()
' CATCH1 muestra el error y retorna la ejecución a la siguiente linea
On Error GoTo CATCH1
a = 1 / 0
' Quitamos el manejador de errores CATCH1 (actual), dejamos que VB haga lo que le parezca
On Error GoTo 0
a = 1 / 0
' CATCH2 muestra el error y finaliza la función/rutina
On Error GoTo CATCH2
a = 1 / 0
' Sin ningún manejador de errores específico, simplemente continuamos a la siguiente línea
On Error Resume Next
a = 1 / 0
Exit Sub
CATCH1:
MsgBox "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
Resume Next
CATCH2:
MsgBox "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
Exit Sub
End Sub
Just in case, if it is not deduced from the code, at any moment of the execution there can be only one active error handler or none at all.