Is there a "Try-catch" in VB 6.1?

3

I'm playing a program made in VB6, I have to perform an execution control in case errors are generated in the following code:

Dim shell As Object
Dim RUTA As String
RUTA = misGlobales.PathReports & "\SLG_Invocador.exe"
Set shell = CreateObject("WSCript.shell")
shell.Run "cmd /C " & RUTA & " " & guidPedido, 0, True

Any ideas on how I could do it?

    
asked by Geraniego 28.03.2018 в 17:40
source

2 answers

2

You can do the following since there is no Try...Catch in V6

Dim sMsg As String

On Error Goto ErrHandler

' todo tu codigo aqui

Exit Function

ErrHandler:
sMsg = "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
GoLogTheError sMsg

This I saw relatively recently in this post: link

    
answered by 28.03.2018 в 17:48
1

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.

    
answered by 28.03.2018 в 18:44