0

everyone

I am writing a C# application that handles all uncaught exceptions in the main routine:

    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainFrame());                     
        }
        catch (Exception e)
        {
            CrashReporter.Report(e);
        }
    }

And when I am running the application (even Release build) from visual studio it works. But when I publish it as click-once and install, in most of the cases, the exceptions won't be caught in the Main function. And the exception stack is something like this:

...
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

I.e. Main is not even in the stack... Why does that happen? Is there any way to do such 'catch all' thing? Why is published vs local build behavior different?


Thanks in advance Serge

Serge
  • 1,027
  • 14
  • 21

3 Answers3

2

I expect that the exception wasn't thrown on the main thread.

Obviously, the other threads don't have Main on the stack (because the thread function is their entry point).

As you are getting a 'nativewindow' callback, this means that the native window is operating on a different thread. You may want to use message passing or use 'Invoke' to relay the callback if you need your code to operate on one thread.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
2

To answer your Is there any way to do such 'catch all' thing? question, check out AppDomain.UnhandledException

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled. ...

and Application.ThreadException events.

This event allows your Windows Forms application to handle otherwise unhandled exceptions that occur in Windows Forms threads. Attach your event handlers to the ThreadException event to deal with these exceptions, which will leave your application in an unknown state. Where possible, exceptions should be handled by a structured exception handling block. ...

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
0

The exception is being thrown in a window callback; those are invoked on the event-dispatch thread. The stack trace you see is the one from that thread, not the main one where your program starts up.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186