3

In a C# windows application I have written code to display all exceptions. I tried the code below. When running in trace mode (pressing F5) it worked (I have written my UI event functions which has created the exceptions). But when I run the standalone exe it does not catch the exception. Instead it is displayed as an unhandled exception.

static void Main()
{
    try
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        MessageBox.Show(ex.StackTrace);
    }
}

Does anybody know about it?

APC
  • 144,005
  • 19
  • 170
  • 281
Muthukumar Palaniappan
  • 1,622
  • 5
  • 25
  • 49

3 Answers3

2

You better use the unhandled exception handler:

AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CatchUnhandledException);

More information on the MSDN:

PVitt
  • 11,500
  • 5
  • 51
  • 85
0

I usually go with this approach:

static void Main()
{
    Application.ThreadException += ExceptionHandler;
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

static void ExceptionHandler(object sender, ThreadExceptionEventArgs e)
{
  const string errorFormat = @"some general message that a error occured";

  //error logging, usually log4.net

  string errMessage = string.Format(errorFormat, e.Exception.Message, e.Exception.StackTrace)
  DialogResult result = MessageBox.Show(errMessage, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

  if (result == DialogResult.No)
  {
    Application.Exit();
  }
}

This displays the exception's message and stack trace to the user, and asks to terminate the application. This is quite usefull in test scenarios or in-house application, but it's generally a bad idea to release detailed stack traces of messages in the wild.

SWeko
  • 30,434
  • 10
  • 71
  • 106
0

Try to add an UnhandledException handler:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((o, e) => { 

      Exception theException = (Exception)e.ExceptionObject;

      /* CODE TO SHOW/HANDLE THE EXCEPTION */
      Debug.WriteLine(theException.Message);
});
Cipi
  • 11,055
  • 9
  • 47
  • 60