You can use the My.Application.Log and My.Log objects to log information about exceptions that occur in your application. These examples show how to use the My.Application.Log.WriteException method to log exceptions that you catch explicitly and exceptions that are unhandled.
For logging tracing information, use the My.Application.Log.WriteEntry method. For more information, see WriteEntry
To log a handled exception
Create the method that will generate the exception information.
The following example shows the complete code for logging a handled exception.
VB
PublicSub ExceptionLogTest(ByVal fileName AsString)
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 & ".")
EndTryEndSub
To log an unhandled exception
Have a project selected in Solution Explorer. On the Project menu, choose Properties.
Click the Application tab.
Click the View Application Events button to open the Code Editor.
This opens the ApplicationEvents.vb file.
Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
On the Declarations menu, choose UnhandledException.
The application raises the UnhandledException event before the main application runs.
Add the My.Application.Log.WriteException method to the UnhandledException event handler.
VB
My.Application.Log.WriteException(e.Exception,
TraceEventType.Critical,
"Application shut down at " &
My.Computer.Clock.GmtTime.ToString)
The following example shows the complete code for logging an unhandled exception.
VB
PrivateSub MyApplication_UnhandledException(
ByVal sender AsObject,
ByVal e As ApplicationServices.UnhandledExceptionEventArgs
) HandlesMe.UnhandledException
My.Application.Log.WriteException(e.Exception,
TraceEventType.Critical,
"Application shut down at " &
My.Computer.Clock.GmtTime.ToString)
EndSub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
This module explores the use of exceptions and the exception handling process in C# console applications. Hands-on activities provide experience implementing exception handling patterns for various coding scenarios.