简体   繁体   中英

Global exception catch works only while debugging the WinForms application

I implemented the following global exception catch in my WinForms application:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyMainForm());
        }
        catch (Exception ex)
        {
            MessageBox.Show("UNHANDLED EXCEPTION: The program will be terminated. Details follow:\n\n" +
                getExceptionInfoWithDebuggerOutput(ex),
                "Global Exception",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
}

Then down the code, an exception is raised (something as this one -- totally due to my forgetfulness):

public partial class MyPage : UserControl
{

    void func1()
    {
        SqlConnectionStringBuilder conStr = null;

        //... later
        conStr.DataSource = strServer;  //<<--- Where exception is raised
    }
}

Now, if I'm debugging my project, I see my Global Exception message box from the global exception handler.

But if I'm not debugging my project and run it as Ctrl+F5, or if I build a Release project, I get the following window instead of the one I coded above:

在此处输入图片说明

Any idea how to make my global exception handler do the processing instead?

You should be hooking an event such as AppDomain.UnhandledException .

These events are raised before the global error handler you're seeing in release mode. This allows you to log errors before bailing out.. in a nicer way.

There are other events that are raised also. For example, Application.ThreadException . Reading the documentation will give you better insights into your specific needs.

I have to note that the error you're seeing is a NullReferenceException .. which would ideally be nicely handled within your code. Still, hooking these events and logging exceptions is a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM