C# ThreadExceptionEventHandler not executing

Status
Not open for further replies.
In fact, none of the handlers I put here work. Not even in an example from MSDN. WTF?

Code:
    internal partial class Form1
    {
        static void Main()
        {
            try
            {
                Form f = new Form();
                f.Load += new EventHandler((object s, EventArgs e) =>
                {
                    throw new WebException();
                });
                Application.ThreadException += (object o, ThreadExceptionEventArgs e) => 
                {
                    MessageBox.Show("ThreadException"); 
                };
                Application.ThreadExit += new EventHandler((object o, EventArgs e) => {
                    MessageBox.Show("Exit"); 
                });
                Application.Run(f);
            }
            catch(Exception e)
            {
                MessageBox.Show("Exception");
            }
        }
    }
}
 

technophile

Ars Legatus Legionis
23,768
The event handlers won't run in the context of that catch, so your catch will never be executed. Try something like this:
Code:
                f.Load += new EventHandler((object s, EventArgs e) =>
                {
                    try
                    {
                        throw new WebException();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Exception");
                    }
                });

The functions will execute in the context of whatever stack trace actually invokes the event, not in the context of your Main() method; they don't get executed immediately.

This might be slightly clearer to you if you rewrite the code to not use anonymous methods:
Code:
                f.Load += new EventHandler(FormLoad);

...

        private static void FormLoad(object s, EventArgs e)
        {
            throw new WebException();
        }

When FormLoad is called by the event, the current execution context will not be within that try...catch block. The same is true when you use the anonymous method as well.
 
technophile":1p40lilh said:
The functions will execute in the context of whatever stack trace actually invokes the event, not in the context of your Main() method; they don't get executed immediately.

Then what are they even FOR? What do they do they do that catch doesn't? It's called THREAD exception, so that's what I expected.

Anyway, what I was looking for was a way to handle any exceptions that I otherwise forgot. Optimally, it would handle the whole application, but one thread was all I asked for.

Is "context of whatever stack trace actually invokes the event" different from the call stack? Because Main is in the call stack.
 

technophile

Ars Legatus Legionis
23,768
Tiiba":1ab7dej7 said:
Is "context of whatever stack trace actually invokes the event" different from the call stack? Because Main is in the call stack.
Main is in the call stack at the time you add the handler, but will not be when the handler is actually executed.

What you're basically doing with an event handler is saying "When this thing happens, execute this function". It's not going to go back and load the call stack of wherever that handler was assigned, it's going to execute that handler as part of whatever call stack raised the event.

technophile":1ab7dej7 said:
The functions will execute in the context of whatever stack trace actually invokes the event, not in the context of your Main() method; they don't get executed immediately.

Then what are they even FOR? What do they do they do that catch doesn't? It's called THREAD exception, so that's what I expected.
The function you specify will be executed when (or if) an unhandled thread exception occurs (or whatever event you hooked it to). You don't want the handler to fire immediately, you want it to fire if/when the event it's hooked to actually occurs.

Anyway, what I was looking for was a way to handle any exceptions that I otherwise forgot. Optimally, it would handle the whole application, but one thread was all I asked for.
Here you go.

Note that there are some exceptions (OutOfMemoryException, for example) that you should never try to handle*; you can't do anything useful with it, and you're likely to make things worse. Note further that the above article is WinForms only -- if you're doing Silverlight or ASP.NET you'll need a different solution (google search terms suggestion: technology + " Handle Unhandled Exception").



* Preemptive PeterB note: You should never try to handle unexpected exceptions at all; you should just crash since your application state is by definition unanticipated. ;)
 

dodexahedron

Ars Praefectus
3,368
Subscriptor++
technophile":a4m5zj5s said:
* Preemptive PeterB note: You should never try to handle unexpected exceptions at all; you should just crash since your application state is by definition unanticipated. ;)

I beg to differ.
Just crashing is always a terrible idea, from a user perspective. It leads to the scary Windows Error Reporting tool launching, which immediately makes people hate your software and/or Windows itself.
Always handle unexpected exceptions in such a way that you notify the user that something unexpected ocurred and that, to protect data integrity as much as possible, the program will terminate now. This also gives you a chance to prepare a crash dump for later debugging.

An unexpected error ocurred. The application will now close, to prevent data corruption.

That may seem ironic to the user if he/she hasn't saved their data at all and thus is going to lose all their work when the app closes... Sometimes an emergency save to a temporary file is in order, in those cases, to allow the user to at least attempt to recover data.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Sometimes an emergency save to a temporary file is in order, in those cases, to allow the user to at least attempt to recover data.

Thius is the wrong approach, instead, while in a *good* state, it should have been auto saving as it went along, then on crashing it should do as little as possible. On restart it should detect the presence of said auto save file and, depending on the complexity prof the app, either present said auto save or indicate the option of recovering it.

If any solution to being in an indeterminate state is to try to do something important whilst in that state said 'solution' is almost certainly not a great solution.
 
Status
Not open for further replies.