2

I often find unhandled exceptions in my console application. Then later it hangs and stops all processes. I'm also forced to restart the program before it will work normally.

Unhandled Exception:

My program is a server program. I don't want it to stop working, because it affects the business.

How can I handle this error?

Poppy Nw
  • 33
  • 2
  • 7
  • 2
    `try` `catch` is the best bet – TheGeneral Oct 09 '18 at 08:43
  • 1
    An unhandled exception is an unexpected and ununderstood exception. Do you really want to write to your database after something unknown went wrong? Stopping the application is a feature, not a problem. – bommelding Oct 09 '18 at 08:48
  • You should handle exceptions you understand and expect at the right places. – bommelding Oct 09 '18 at 08:49
  • try - catch(Exception) should do the job. But catching all exceptions is a design smell for a reason. Please see the link: https://softwareengineering.stackexchange.com/questions/164256/is-catching-general-exceptions-really-a-bad-thing – Sisir Oct 09 '18 at 08:53
  • I've already try catch. But it's might not cover this situation. So I get this error. – Poppy Nw Oct 09 '18 at 08:59

1 Answers1

4

Register a global exception handler in your main method like this:

//Add handler to handle the exception raised by additional threads
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Then handle all the unhandled exception in CurrentDomain_UnhandledException method.

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    //Your logic here, for ex., log the exception somewhere
}
Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
  • An do write the value of `e.IsTerminating`. – bommelding Oct 09 '18 at 08:53
  • Thank you for your answer. When I add function and just log information then force to exit program always. I'll add command Console.ReadLine(); but I don't know that have another side effect or not? like memory or performance. – Poppy Nw Oct 18 '18 at 06:15