开发者

VB6-how to create log file in VB6 while launching application

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 sa开发者_如何转开发ve 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜