Search code examples
c#winformscrashappdomainunhandled-exception

Windows Forms Unhandled Exception Crash


I have code that caters for my winforms application to handle an an unhandled exception. My application however still crash.

I do, at this stage, have no understanding why this behavior is. I would appreciate your assistance.

Here is my code:

 [STAThread]
    private static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        bool result;
        var mutex = new System.Threading.Mutex(true, "MyApplication", out result);
        if (!result)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }
        Application.ThreadException += ApplicationThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
        Memory.frmMain = new MainForm();
        Application.Run(new MyApplicationContext());
        GC.KeepAlive(mutex);
    }
    public static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show(((Exception)e.ExceptionObject).Message);
        ((Exception)e.ExceptionObject).AddLog();
        Memory.processtranslations.IsProcessing.Enabled = true;
    }
    public static void ApplicationThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message);
        e.Exception.AddLog();
        Memory.processtranslations.IsProcessing.Enabled = true;
    }

Solution

  • Try to add [HandleProcessCorruptedStateExceptions] attribute to your Main method. What's more, get your main loop into try..catch:

    [HandleProcessCorruptedStateExceptions]
    static void Main(string[] args)
    {
     //other code
      
      try
      {
        Application.Run(new MyApplicationContext());
      }catch(Exception)
      {
        //...
      }
    }