I want to log the exceptions occurred during execution of my app. Before this I handled it with message box. I am new to VB 6.
Please provide some sample code to create log file and to save exception messages.
Thanks..
You need error handlers, using On Error Goto, so that you can execute your own code when an error occurs. (BTW in VB6 they are called errors not exceptions.) The free tool MZTools is excellent - it can automatically insert the On Error Goto and an error handler which includes the name of the current routine.
You also need a general routine that logs error details to a file, a little bit like this below. Health warning - I've just typed this straight in without testing it (air code).
Sub MySub()
On Error Goto ErrHandler
'... Do something ...'
On Error Goto 0
Exit Sub
ErrHandler:
Call LogError("MySub", Err, Error$) ' passes name of current routine '
End Sub
' General routine for logging errors '
Sub LogError(ProcName$, ErrNum&, ErrorMsg$)
On Error Goto ErrHandler
Dim nUnit As Integer
nUnit = FreeFile
' This assumes write access to the directory containing the program '
' You will need to choose another directory if this is not possible '
Open App.Path & App.ExeName & ".log" For Append As nUnit
Print #nUnit, "Error in " & ProcName
Print #nUnit, " " & ErrNum & ", " & ErrorMsg
Print #nUnit, " " & Format$(Now)
Print #nUnit
Close nUnit
Exit Sub
ErrHandler:
'Failed to write log for some reason.'
'Show MsgBox so error does not go unreported '
MsgBox "Error in " & ProcName & vbNewLine & _
ErrNum & ", " & ErrorMsg
End Sub
Bonus suggestion: roll your own stack trace.
Bonus suggestion 2: switch off the error handlers in the IDE with something like this If Not IsInIDE() Then On Error Goto Handler, using the IsInIDE function from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With