Search code examples
c#.netwinformsexceptionmessagebox

Do not see MessageBox


Why do I not see the MessageBox with exception details when I run my program by executing exe fine in bin debug folder?

I do see the exception when I debug (run) the program from Visual Studio.

[STAThread]
static void Main()
{
    try
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    catch (Exception ex)
    {
        if (MessageBox.Show(
            string.Format("There were unhandeled exceptions. Would you like to continue using this program?"),
            "Fatal Error",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No)
                Application.Exit();
    }
}

Edit
Here is the code that generates the exception:

private void button1_Click(object sender, EventArgs e) {
    int num = 1;
    num = num / (num - num);
}

Solution

  • Add this line:

    try 
    {
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
        ...
    

    Apparently the default is different when debugging. I don't know the details about that.

    Also note that your if(...) Application.Exit(); is not really useful here, and it shouldn't.
    Don't try to restart or anything.