HOW TO:在 Visual Basic 中記錄例外狀況
您可以使用 My.Application.Log 和 My.Log 物件,記錄應用程式中所發生的例外狀況資訊。 這些範例會顯示如何使用 My.Application.Log.WriteException 方法,記錄您明確攔截的例外狀況,以及未處理的例外狀況。
如需記錄追蹤資訊,請使用 My.Application.Log.WriteEntry 方法。 如需詳細資訊,請參閱 WriteEntry。
若要記錄已處理的例外狀況
建立會產生例外狀況資訊的方法。
Public Sub ExceptionLogTest(ByVal fileName As String) End Sub
使用 Try...Catch 區塊,攔截例外狀況。
Try Catch ex As Exception End Try
將會產生例外狀況的程式碼放入 Try 區塊中。
取消 Dim 和 MsgBox 行的註解,會造成 NullReferenceException 例外狀況。
' Code that might generate an exception goes here. ' For example: ' Dim x As Object ' MsgBox(x.ToString)
在 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
若要記錄未處理的例外狀況
在 [方案總管] 中選取專案。 在 [專案] 功能表上,選擇 [屬性]。
按一下 [應用程式] 索引標籤。
按一下 [檢視應用程式事件] 按鈕,開啟 [程式碼編輯器]。
這會開啟 ApplicationEvents.vb 檔案。
在程式碼編輯器中開啟 ApplicationEvents.vb 檔案。 在 [一般] 功能表上,選擇 [MyApplication 事件]。
在 [宣告] 功能表中,選擇 [UnhandledException]。
應用程式會在主應用程式執行之前引發 UnhandledException 事件。
將 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
請參閱
工作
逐步解說:判斷 My.Application.Log 寫入資訊的位置 (Visual Basic)
逐步解說:變更 My.Application.Log 寫入資訊的位置 (Visual Basic)
參考
Microsoft.VisualBasic.Logging.Log