[C#] Catching exceptions in Main()

Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
As title... I've encased the contents of the Main() method (as the entry point for a Windows form) in Program.cs in a try {} catch {} block. This all works fine in debugging mode, but as soon as I compile, run and get an exception for whatever reason, I get the normal error message telling me there's been an error. Why is it not catching the exception? :confused:
 
Well, here's my Main() method code:

Code:
        [STAThread]
        private static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new formMultiBackup(args));
            }
            catch (Exception exception)
            {
                // Exception caught - not much we can do about
                // it at this stage, but we can log it at least

                // Inform user
                string title = "Error";
                string message = exception.Message;
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                MessageBoxIcon icon = MessageBoxIcon.Error;
                MessageBox.Show(message, title, buttons, icon);

                // Log error
                LogError(exception);
            }
        }
and my exception is being thrown like this:
Code:
        private void buttonTest_Click(object sender, EventArgs e)
        {
                throw new Exception("This is a test exception.");
        }
When I click this button, I get exactly the same message on the window that pops up when there's an unhandled exception, so either it's not being caught, or it's getting rethrown for some reason :confused:

Cheers.
 
Last edited:
That's weird... I just tried what you said and it worked fine, even after being compiled... It even works fine when I stick it in the formMultiBackup constructor. However, it doesn't work when I put it in the button click event handler :confused:
 
Hmm, I've just tested that with a couple of assertions, and the thread that handles the event has the same ID as the thread that starts the form object. Also, the debugger seems fine with an exception being thrown from the event handler.
 
Yup. I've put an assertion in the catch block, and that's getting fired when the exception occurs during debugging.

I tried it again when it's compiled (using another exception in the catch block this time, rather than an assertion) and control does not appear to be entering the catch block.
 
Thanks, this almost works :p

When an exception is thrown at some point during the program's execution, the event handler I added in Program.cs catches the event, does its stuff and the program continues, but when I try this in Debug mode (not Release mode), I get an "Exception was unhandled by user code" message come up...
 
Back
Top Bottom