如何:在 Visual Basic 中记录异常

更新:2007 年 11 月

可以使用 My.Application.Log 和 My.Log 对象记录有关应用程序中发生的异常的信息。本文中的这些示例演示如何使用 My.Application.Log.WriteException 方法记录可以显式捕获的异常和未处理的异常。

若要记录跟踪信息,请使用 My.Application.Log.WriteEntry 方法。有关更多信息,请参见 WriteEntry 方法(My.Application.Log 和 My.Log)

记录已处理的异常

  1. 创建将生成异常信息的方法。

    Public Sub ExceptionLogTest(ByVal fileName As String)
    End Sub
    
  2. 使用 Try...Catch 块捕获异常。

    Try
    Catch ex As Exception
    End Try
    
  3. 将可能会生成异常的代码放入 Try 块中。

    取消注释 Dim 和 MsgBox 行会导致 NullReferenceException 异常。

    ' Code that might generate an exception goes here.
    ' For example:
    '    Dim x As Object
    '    MsgBox(x.ToString)
    
  4. 在 Catch 块中,使用 My.Application.Log.WriteException 方法写入异常信息。

    My.Application.Log.WriteException(ex, _
        TraceEventType.Error, _
        "Exception in ExceptionLogTest " & _
        "with argument " & fileName & ".")
    

记录未处理的异常

  1. 在“解决方案资源管理器”中选择一个项目。在“项目”菜单上,选择“属性”。

  2. 单击“应用程序”选项卡。

  3. 单击“查看应用程序事件”按钮打开代码编辑器。

    此操作将打开 ApplicationEvents.vb 文件。

  4. 在代码编辑器中保持 ApplicationEvents.vb 文件处于打开状态。在“常规”菜单中选择“MyApplication 事件”。

  5. 在“声明”菜单上,选择“UnhandledException”。

    应用程序在主应用程序运行之前引发 UnhandledException 事件。

  6. 将 My.Application.Log.WriteException 方法添加到 UnhandledException 事件处理程序。

    My.Application.Log.WriteException(e.Exception, _
        TraceEventType.Critical, _
        "Application shut down at " & _
        My.Computer.Clock.GmtTime.ToString)
    

示例

此示例演示用于记录已处理异常的完整代码。

Public Sub ExceptionLogTest(ByVal fileName As String)
    Try
        ' Code that might generate an exception goes here.
        ' For example:
        '    Dim x As Object
        '    MsgBox(x.ToString)
    Catch ex As Exception
        My.Application.Log.WriteException(ex, _
            TraceEventType.Error, _
            "Exception in ExceptionLogTest " & _
            "with argument " & fileName & ".")
    End Try
End Sub

下一示例演示用于记录未处理异常的完整代码。可以使用“项目设计器”来访问代码编辑器中的应用程序事件。有关更多信息,请参见如何:处理应用程序事件 (Visual Basic)

Private Sub MyApplication_UnhandledException( _
    ByVal sender As Object, _
    ByVal e As ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
    My.Application.Log.WriteException(e.Exception, _
        TraceEventType.Critical, _
        "Application shut down at " & _
        My.Computer.Clock.GmtTime.ToString)
End Sub

请参见

任务

如何:写入日志消息

演练:确定 My.Application.Log 写入信息的位置

演练:更改 My.Application.Log 写入信息的位置

概念

使用 Application 日志 (Visual Basic)

参考

My.Application.Log 对象

My.Log 对象

WriteEntry 方法(My.Application.Log 和 My.Log)

WriteException 方法(My.Application.Log 和 My.Log)