Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging unhandled exceptions to a log file

How can I log unhandled exceptions to a log file for a WinForms application so it is easy to determine the source of an exception?

like image 866
Bhaumik Patel Avatar asked Oct 16 '12 10:10

Bhaumik Patel


People also ask

How do I log unhandled exceptions?

If you use try/catch, just add the logging code to the catch block - this is to pick up unhandled exceptions, i.e. those that did not get caught in a try/catch block.

How do I create an exception to a log file?

To log a handled exceptionCreate the method that will generate the exception information. Use a Try...Catch block to catch the exception. Put the code that could generate an exception in the Try block. Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.

How does Python handle unhandled exceptions?

An unhandled exception displays an error message and the program suddenly crashes. To avoid such a scenario, there are two methods to handle Python exceptions: Try – This method catches the exceptions raised by the program. Raise – Triggers an exception manually using custom exceptions.


2 Answers

Firstly, you will need to catch unhandled exceptions. Add the VB.Net version of this code to your main program:

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += ApplicationThreadException;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

Then add the event handlers:

static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = e.ExceptionObject as Exception;
    if (ex != null)
    {
       Console.WriteLine("Unhandled exception: {0}", e.Exception);      
    }
}

static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
    Console.WriteLine("Unhandled application exception: {0}", e.Exception);
}

Then you can log the errors with your chosen log method.. (Sorry for the C# code!)

like image 90
stuartd Avatar answered Oct 10 '22 06:10

stuartd


In your Sub Main, or the constructor for your start up form, add the following code:

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler

Then, add the following method to your Sub Main, or add it as a shared method in any other class/form:

Public Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    If TypeOf e.ExceptionObject Is Exception Then
        Dim ex As Exception = CType(e.ExceptionObject, Exception)
        ' Log the exception
    End If
End Sub
like image 45
Steven Doggart Avatar answered Oct 10 '22 04:10

Steven Doggart