2010-01-13 58 views
5

我想记录执行我的应用程序期间发生的异常。在此之前,我用消息框处理它。我是新来的VB 6VB6-如何在启动应用程序时在VB6中创建日志文件

请提供一些示例代码来创建日志文件,并保存异常消息。

谢谢..

+0

http://articles.techrepublic.com.com/5100-10878_11-5798663.html 即似乎几乎是你想要的。 – johnnyArt 2010-01-13 08:19:08

+0

感谢MarkJ。 :) – Royson 2010-01-14 04:48:05

回答

6

你需要错误处理,使用On Error Goto,这样在发生错误时,你可以执行自己的代码。 (在VB6中,它们被称为错误不是例外。)免费工具MZTools非常好 - 它可以自动插入On Error Goto和包含当前例程名称的错误处理程序。

您还需要一个记录错误的详细信息到一个文件中,有点像下面这样一个一般常规。健康警告 - 我只是直接输入,没有测试(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 

奖励建议:roll your own stack trace
加成建议2:从here关闭错误处理与像这样If Not IsInIDE() Then On Error Goto Handler IDE中,使用IsInIDE函数

相关问题