共用方式為


如何:在 Visual Basic 中記錄例外狀況

您可以使用 My.Application.LogMy.Log 物件來記錄應用程式中發生的例外狀況相關信息。 這些範例示範如何使用 My.Application.Log.WriteException 方法來記錄您明確攔截的例外狀況,以及未處理的例外狀況。

若要記錄追蹤資訊,請使用 My.Application.Log.WriteEntry 方法。 如需詳細資訊,請參閱 WriteEntry

若要記錄已處理的例外狀況

  1. 建立將產生例外狀況資訊的方法。

    Public Sub ExceptionLogTest(ByVal fileName As String)
    End Sub
    
  2. 使用 Try...Catch 區塊來捕捉例外狀況。

    Try
    Catch ex As Exception
    End Try
    
  3. 將可能會產生例外狀況的程式代碼放在 區塊中 Try

    取消註解 DimMsgBox 行,以引發 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 & ".")
    

    下列範例顯示記錄已處理例外狀況的完整程序代碼。

    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
    

若要記錄未處理的例外狀況

  1. [方案總管] 中選取專案。 在 [ 專案] 功能表上,選擇 [ 屬性]。

  2. 按一下 [應用程式] 索引標籤。

  3. 按兩下 [ 檢視應用程式事件 ] 按鈕以開啟程式代碼編輯器。

    這會開啟ApplicationEvents.vb檔案。

  4. 在程式代碼編輯器中開啟ApplicationEvents.vb檔案。 在 [ 一般] 功能表上,選擇 [MyApplication 事件]。

  5. 在 [ 宣告] 功能表上,選擇 [未處理的Exception]。

    應用程式會在主要應用程式執行之前引發 UnhandledException 事件。

  6. My.Application.Log.WriteException 方法新增至 UnhandledException 事件處理程式。

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

    下列範例顯示記錄未處理的例外狀況的完整程序代碼。

    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
    

另請參閱