5

I've read in this post that to avoid the “program stopped working” dialog ,I need to catch the unhandled exception from the AppDomain.

 public Form1()
 {
  ///Code
   AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  ///more code
 }

     void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var excep = e.ExceptionObject;

        //Writing the exception to log file with the stack flow
        Logger.Logger.LogException("UNHANDLED EXCEPTION:"+Environment.NewLine +excep.ToString(), this);

        //Terminate the logger (manual event waiting for file write to finish)
        Logger.Logger.Terminate();
        Environment.Exit(1);
    }

But when I get inhaled exception. I can see it written on the log, but The application shows the “program stopped working” dialog. can it be caused by the Logger.Terminate line? (again - the terminate command waits until all logs were written to the log file)

Community
  • 1
  • 1
Izikon
  • 902
  • 11
  • 23
  • 1
    It is possible for your event handler to crash as well. That Terminate() method sounds pretty risky. Even Environment.Exit() can fail, it still runs the finalizers. Or something silly like a bug in the Logger class, won't get better when you use it in the event handler. In general, something nasty happened in your program so the odds that it can destabilize your event handler as well are never zero. You are also fairly late subscribing the event, it should be done in the Main() method before doing anything else. – Hans Passant Nov 27 '15 at 14:18
  • It's also possible that the event handler never gets called. Some exceptions (`StackOverflowException`) can take down the whole process before any handler gets a chance to run. –  Nov 27 '15 at 14:27
  • Guys- I see the unhandle exception in the log file and also the finilizing the log file. so this event does get processed. Also I do have in the main the same event catch on Thread exception (thanks!) – Izikon Nov 30 '15 at 08:04

1 Answers1

0

Ideally, you want to avoid the “program stopped working” dialog because, well, you want to avoid the “program stopped working” condition to begin with. If not, if you just want to log the error and let the program end gracefully, then the program has to actually end gracefully.

If you exit the program with Environment.Exit(1), you´re pretty much telling the operating system, "hey, I bugged out!", which is the opposite of a graceful termination. Try exiting with a 0 code and see if it makes any difference.

João Mendes
  • 1,719
  • 15
  • 32