Search code examples
c#exceptionunhandled-exception

Unhandled Exception handling in C#


I am trying to understand how a C# program handles an unhandled Exception.

I am doing my testing in a windows forms project, If the answer is different in other project types, please let me know.

I am running the program from the .exe file and not from the visual studio debugger.

Code:

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //timer1.Interval = 10000
    private void timer1_Tick(object sender, EventArgs e)
    {
        //throw new Exception(Thread.CurrentThread.ManagedThreadId.ToString() + " This is an exception");
    }
}
static class Program
{

    static Form1 newForm;

    static void Main()
    {
        Thread FormThread = new Thread(NewForm);
        FormThread.Start();

        Thread.Sleep(5000);

        //throw new Exception(Thread.CurrentThread.ManagedThreadId.ToString() + " This is an exception");
    }

    static void NewForm()
    {
        newForm = new Form1();
        Application.Run(newForm);
    }
}

My question is what will be the windows response for an unhandled Exception in a C# program?

in the above example:

If the exception is thrown from the timer1_Tick function (by deleting the comment prefix) I am getting the following message: timer1_Tick Exception

If the exception is thrown from the Main function (by deleting the comment prefix) I am getting the following message: Main Exception

why I am getting 2 different messages and how the windows/program "choose" which message to pop.

Thank you.


Solution

  • In a WinForms application, event handlers are invoked by the WindowsFormsSynchronizationContext. When an event handler throws an unhandled exception, the context handles it by displaying the first error dialog. At that point the synchronization context (which is simply a message pump) is still running and it could still proceed handling other events, so you are given a choice.

    The Main method, in contrast, is invoked by the operating system itself, to start the application. If there is an unhandled exception there, WIndows has no option but to terminate the application, and it shows the second dialog to inform you of this.