我希望记录应用程序执行过程中发生的异常情况。之前我使用消息框处理异常。我是VB 6的新手。
请提供一些示例代码,以创建日志文件并保存异常信息。
谢谢。
On Error Goto
,以便在出现错误时执行自己的代码。(顺便提一句,在VB6中它们被称为“错误”,而不是“异常”)免费工具MZTools非常好用 - 它可以自动插入On Error Goto
和一个包括当前程序名称的错误处理程序。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
额外建议:自己编写堆栈跟踪。
额外建议2:在IDE中关闭错误处理程序,可以使用类似于 If Not IsInIDE() Then On Error Goto Handler
的语句,并使用IsInIDE
函数。