共用方式為


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

您可以使用 My.Application.Log 和 My.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 區塊中。

    取消 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 & ".")
    

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

    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. 在 [宣告] 功能表中,選擇 [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)
    

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

    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
    

請參閱

工作

如何:寫入記錄訊息 (Visual Basic)

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

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

參考

Log

WriteEntry

WriteException

概念

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