Share via


HOW TO:在 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

下一個範例會顯示記錄未處理之例外狀況的完整程式碼。您可以使用 [專案設計工具],在「程式碼編輯器」中存取應用程式事件。如需詳細資訊,請參閱 HOW TO:處理應用程式事件 (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

請參閱

工作

HOW TO:寫入記錄訊息

逐步解說:判斷 My.Application.Log 寫入資訊的位置

逐步解說:變更 My.Application.Log 寫入資訊的位置

概念

在 Visual Basic 中使用應用程式記錄檔

參考

My.Application.Log 物件

My.Log 物件

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

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