How to know whether VBA runtime environment is stopped or running? - events

In my VBA code, I get a runtime exception (say divide by zero) and after pressing 'End' in the error box, the VBA runtime gets stopped.
During this stop, my global Objects are getting cleared. I want these objects to retain their values. Because, when I start over again, since these objects are Nothing, I am having issues.
Is there any event in VBA which will get triggered when my runtime gets stopped?? Or is there any way to know whether VBA is still running or stopped?

In VBA, an unhandled exception clears global variables. So add error handlers to your VBA procedures.
Here is a transcript of a session in the Immediate window, using the 2 procedures included below.
MyGlobal = "foo"
Call DemoDivideByZero
? Chr(39) & MyGlobal & Chr(39)
''
MyGlobal = "foo"
Call DemoDivideByZero2
Error 11 (Division by zero) in procedure DemoDivideByZero2
? Chr(39) & MyGlobal & Chr(39)
'foo'
A procedure without an error handler ...
Public Sub DemoDivideByZero()
Debug.Print 2 / 0
End Sub
A version with an error handler ...
Public Sub DemoDivideByZero2()
Dim strMsg As String
On Error GoTo ErrorHandler
Debug.Print 2 / 0
ExitHere:
On Error GoTo 0
Exit Sub
ErrorHandler:
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure DemoDivideByZero2"
Debug.Print strMsg
GoTo ExitHere
End Sub
However I'm unsure whether including error handlers in your procedures will be enough to preserve your global variable values. I avoid using globals.

Which global objects do you have? At startup you need to initialise them.

Related

How to fix Wscript.CreateObject returning empty when prefix is specified?

I'm trying to process event handlers for ADODB.Command object. When I specify a prefix, Wscript.CreateObject exits the function without issuing any error message. When the prefix is removed from Wscript.CreateObject, the ADODB.Command object is created.
Additionally when setting On Error Resume Next, Wscript.CreateObject returns and empty object.
Can someone please tell me what I'm doing wrong ?
Code:
DIM tsqlcmd
On Error Goto 0
SET tsqlcmd = WScript.CreateObject("ADODB.Command", "ehdlr_tsqlcmd_")
.....
Private Sub ehdlr_tsqlcmd_ExecuteComplete( RecordsAffected, pError, adStatus, pCommand, pRecordset, pConnection)
' place any code you desire here, for example
If adStatus = STATUS_adStatusOK Then
MsgBox( "tsqlcmd_ExecuteComplete Records affected = " & RecordAffected)
Else
MsgBox( "tsqlcmd_ExecuteComplete ExecuteComplete Status = " & adStatus)
End If
End Sub

How to pass error back to calling function?

What is the best way in VB6 to pass an error back to the calling function?
1 On Error Resume Next
2 ' do something
3 If Err.Number <> 3026 Or Err <> 0 Then ?????????
How would you send the error in Line 3 back to the calling function? Is the following the only way to achieve this?
errNum = Err.Number
On Error Goto 0
Err.Raise errNum
Use On Error GoTo and re-raise the error in the handler with Err.Raise.
Private Function DoSomething(ByVal Arg as String)
On Error GoTo Handler
Dim ThisVar as String
Dim ThatVar as Long
' Code here to implement DoSomething...
Exit Function
Handler:
Err.Raise Err.Number, , "MiscFunctions.DoSomething: " & Err.Description
End Function
You'll then be able to get the error number and description in the caller via Err.Number and Err.Description.
If the caller is also using On Error GoTo, you'll see them in the handler there.
If the caller is using On Error Resume Next, then you can still use those same variables inline.
I prefer the first option, using On Error Goto in all functions and subs, because it seems like the natural way to use VB6's built-in error raising features. You can also update the description in the called function's handler, like the example above, and get a pseudo call stack you can eventually log or display to yourself during debugging.
More VB6 error handling thoughts here:
Is it possible to retrieve the call stack programmatically in VB6?
How to clean up error handling in a function?
Why not add ByRef errorCode as Long to the called function's args and set it equal to Err.Number after ' do something
Or you could have a public field called ErrorCode as Long that you could set after ' do something
I have worked with a lot of industrial control APIs and both of these methods have been used.
You can easily send the error to the upper (calling) sub/function as long as the function that raises the error does not have (ON ERROR RESUME ---), that way, error handling is left in the upper level only. Otherwise you will have to handle the error inside the called function
Private Sub Command1_Click()
Dim test As Integer
On Error Resume Next
test = myFunction 'Calling a function that is known to have an error
If Err <> 0 Then
MsgBox "MyFunction failed because:" & Err.Description 'Error is passed
End If
End Sub
'--------------------------
Function myFunction() As Integer
Dim i As Integer
i = 1
i = 4 / 0 'This will raise an Error, and control returns to the calling sub
i = 2 'This will never get executed
myFunction = i
End Function
If you simply want to pass the error back to the original caller without handling it, then you want to remove any ON ERROR in the child function:
Public Sub ParentSub()
On Error GoTo ErrorHandler
' do something
Call ChildSub()
' do something
Exit Sub
ErrorHandler:
' handle the error here
End Sub
Public Sub ChildSub()
' do something
' if there is an error here, the error will be handled in ErrorHandler of ParentSub
End Sub
or if you want to handle it in both subs:
Public Sub ParentSub()
On Error GoTo ErrorHandler
' do something
Call ChildSub()
' do something
Exit Sub
ErrorHandler:
' handle the error here
End Sub
Public Sub ChildSub()
On Error GoTo ErrorHandler
' do something
Exit Sub
ErrorHandler:
' handle the error here and pass it back to the ParentSub to handle it as well
Err.Raise Err.Number
End Sub

VB6 Exception Handling within the calling procedure

I have two procedures procA and procB. procA is calling procB. An exception occurs within procB. I can handle the exception within procB, but i like to handle it within procA and this is what i did not get to work. I'm not very familiar with VB6 but i think this should be possible because MSDN says:
If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error. Control returns to the calling procedure. If the calling procedure has an enabled error handler, it is activated to handle the error.
What i'm doing wrong?
Now the code fragments:
Private Sub procA()
On Error GoTo ErrHnd
...
procB obj
Exit Sub
ErrHnd:
MsgBox Err.Description, vbInformation, Me.caption
End Sub
Public Sub procB(ByRef rec As Object)
On Error GoTo ErrHnd
... Exception occurs within DAO Recordset Operation
Exit Sub
ErrHnd:
Select Case Err.Number
Case 3022
Err.Raise vbObjectError + 9999, Err.Source, "Error Text"
Case Else
...
End Select
End Sub
I also tried to turn off exception handling within procB (On Error Goto 0) but it seems that procA never gets the Exception.
Thanks for your help.
Edit: Additional information:
Exception Raised from DAO.Recordset Object.
I also tried to completele remove exception handling within procB with no effect.
procA exists in another file then procB (data.cls, frmListArtikel.frm).
Solution: I didn't know that it makes a difference how the programm is executed. If i start it from the IDE, the Exception does not get handled by procA. If i start the EXE (previously making it from the IDE) from the Explorer, the Exception gets handled as desired by procA.
You can only have one active error handler at a time. If you activate in procb, procb will handle.
you may also need to check your editor settings. choose the option "Tools > Options > General tab" "break in class module"
Code sample 1. you will receive error 6 in procA:
Private Sub Form_Load()
Call procA
End Sub
Private Sub procA()
On Error GoTo errhan
procB
Exit Sub
errhan:
Debug.Print "proca handle"
End Sub
Private Sub procB()
Err.Raise 6
End Sub
Code sample 2. You will receive error 7 in procA:
Private Sub Form_Load()
Call procA
End Sub
Private Sub procA()
On Error GoTo errhan
procB
Exit Sub
errhan:
Debug.Print "proca handle"
End Sub
Private Sub procB()
On Error GoTo errhan
Err.Raise 6
errhan:
Err.Raise 7
End Sub
Check your editor settings and choose the option "Tools > Options > General tab" "Break on Unhandled Errors"
check this link: http://www.fmsinc.com/tpapers/vbacode/debug.asp

VB6 - How to catch exception or error during runtime

I developed an application in VB6. In client's environment it raises runtime errors which I can't reproduce under debugger. Is there any way to get the stacktrace or location of error?
I created log file and
I used
Err.Description,Err.Source
but it gives blank values.
Please help me.
my method(......
On Error GoTo Error_Handler
.........
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
You've probably done something to clear the Err object before writing to the log file. This is very, very easy to do. What you'll want to do is as soon as you detect an error has occurred, grab the error message before doing anything else. Then pass the error message to whatever logging routine you're using. E.g.:
Dim sMsg As String
On Error Goto ErrHandler
' ...code here...
Exit Function
ErrHandler:
sMsg = "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
GoLogTheError sMsg
BTW, thanks for your guys' answers helping me. I'm about half a decade late to the game of VB6. I don't do windows unless forced to. ;)
Anyhow, when doing your error checking, say among 3000 individual record query insertions, I learned a couple tricks. Consider this block of code:
'----- order number 1246-------
On Error Goto EH1246:
sSql="insert into SalesReceiptLine ( CustomerRefListID,TemplateRe..."
oConnection.Execute sSQL
sSql="SELECT TxnID FROM SalesReceiptLine WHERE RefNumber='1246'..."
oRecordset.Open sSQL, oConnection
sTxnId = oRecordset(0)
oRecordset.Close
sSql="INSERT INTO SalesReceiptLine (TxnId,SalesReceiptLineDesc,Sal..."
oConnection.Execute sSQL
EH1246:
IF Err.Number<>0 THEN
sMsg = sMsg & "Order # 1246; sTxnId = " & sTxnId & _
vbCrLf & Err.Number & ": " & Err.Description & vbCrLf
sErrOrders = sErrOrders & "1246,"
End If
On Error GoTo -1
'----- order number 1247-------
On Error Goto EH1247:
When not testing for Err.Number, you'll get a 0: on every order handled. (maybe you don't want that). The On Error GoTo -1 resets the error so that it will work again. Apparently, Err only works "once".
I wrote a php script to build the VB6 source code to run some 8000 odbc queries... :P
Do you definitely, positively have an Exit Function just above the Error_Handler:?
my method(......
On Error GoTo Error_Handler
........
Exit Sub
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
"Exit Sub" should be added before you handle the Error_Handler function.....

what is the better way to handle errors in VB6

I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this
First of all, go get MZTools for Visual Basic 6, its free and invaluable. Second add a custom error handler on every function (yes, every function). The error handler we use looks something like this:
On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
LogError "Error " & Err.Number & " (" & Err.Description & ") in line " & Erl & _
", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}"
Then create a LogError function that logs the error to disc. Next, before you release code add Line Numbers to every function (this is also built into MZTools). From now on you will know from the Error Logs everything that happens. If possible, also, upload the error logs and actually examine them live from the field.
This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors. If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it. If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an "unknown state" and that "bad things" are probably going happen. Obviously use friendly terms to keep the user informed, but not frightened.
a simple way without additional modules, useful for class modules:
pre-empt each function/subs:
On Error Goto Handler
handler/bubbleup:
Handler:
Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description
voila, ghetto stack trace.
I use a home-grown Error.bas module to make reporting and re-raising less cumbersome.
Here's its contents (edited for length):
Option Explicit
Public Sub ReportFrom(Source As Variant, Optional Procedure As String)
If Err.Number Then
'Backup Error Contents'
Dim ErrNumber As Long: ErrNumber = Err.Number
Dim ErrSource As String: ErrSource = Err.Source
Dim ErrDescription As String: ErrDescription = Err.Description
Dim ErrHelpFile As String: ErrHelpFile = Err.HelpFile
Dim ErrHelpContext As Long: ErrHelpContext = Err.HelpContext
Dim ErrLastDllError As Long: ErrLastDllError = Err.LastDllError
On Error Resume Next
'Retrieve Source Name'
Dim SourceName As String
If VarType(Source) = vbObject Then
SourceName = TypeName(Source)
Else
SourceName = CStr(Source)
End If
If LenB(Procedure) Then
SourceName = SourceName & "." & Procedure
End If
Err.Clear
'Do your normal error reporting including logging, etc'
MsgBox "Error " & CStr(ErrNumber) & vbLf & "Source: " & ErrSource & vbCrLf & "Procedure: " & SourceName & vbLf & "Description: " & ErrDescription & vbLf & "Last DLL Error: " & Hex$(ErrLastDllError)
'Report failure in logging'
If Err.Number Then
MsgBox "Additionally, the error failed to be logged properly"
Err.Clear
End If
End If
End Sub
Public Sub Reraise(Optional ByVal NewSource As String)
If LenB(NewSource) Then
NewSource = NewSource & " -> " & Err.Source
Else
NewSource = Err.Source
End If
Err.Raise Err.Number, NewSource, Err.Description, Err.HelpFile, Err.HelpContext
End Sub
Reporting an error is as simple as:
Public Sub Form_Load()
On Error Goto HError
MsgBox 1/0
Exit Sub
HError:
Error.ReportFrom Me, "Form_Load"
End Sub
Reraising an error is as simple as calling Error.Reraise with the new source.
Although it is possible to retrieve the Source and Procedure parameters from the call stack if you compile with symbolic debug info, it's not reliable enough to use in production applications
ON ERROR GOTO
and the
Err
object.
There is a tutorial here.
Yes, take Kris's advice and get MZTools.
You can add line numbers to section off areas of complex procedures, which ERL will report in the error handler, to track down which area is causing the error.
10
...group of statements
20
...group of statements
30
...and so on
Use on
dim errhndl as string
on error goto errhndl
errhndl:
msgbox "Error"
Use the On Error statement and the Err object.

Resources