2

I have a console application written in C# code. Let's assume that it's the most simple application just like Hello World example:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += 
              CurrentDomain_UnhandledException;
        int zero = 0;
        int i = 10 / zero;
    }

    static void CurrentDomain_UnhandledException(
                  object sender, UnhandledExceptionEventArgs e)
    {
        Console.WriteLine("exception");
    }
}

However, I want to handler the DevideByZero exception in the global exception handler, but without exiting the application through Environment.Exit().

Is it possible at all? How?

Note:

I've already seen these questions, but they're all terminating. The exception gets raised again and again.

.NET Global exception handler in console application

Global exception handling in c# (console application)

Community
  • 1
  • 1

3 Answers3

3

This is such a horribly bad idea that I wouldn't be surprised if it was purposely made very difficult or impossible to accomplish.

If the Unhandled exception handler ever gets called, your program is by definition in an unknown and most likely corrupt state. The only reasonable thing to do is to terminate the program as quickly as possible, after logging the error and maybe trying to save any critical data. Even that's a risk, because the error could have happened in the logger ... or in saving data during normal shutdown.

You want to catch the divide by 0 exception? And are you going to check where that exception occurred so that you only catch your own errors. Or is it okay if you blindly ignore when somebody else's code throws a divide by 0 exception?

And even if you can do that, what are you going to do when the exception occurs? It's not like you can just jump back to where you were and continue. The stack has been unwound and all context lost.

You do not want to do this. Really. Write your code so that it won't divide by 0. Or use try/catch. That's what it's for.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
1

I think you can get it resolved using try catch block something like:-

  try { 
     int zero = 0; 
     int i = 10 / zero; 
     } 
  catch (DivideByZeroException) 
   {
   }
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Try this (add a handler to 'Application.ThreadException' too):

static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += 
          CurrentDomain_UnhandledException;

    Application.ThreadException +=
     new System.Threading.ThreadExceptionEventHandler(
                Application_ThreadException);

   Application.SetUnhandledExceptionMode(
     UnhandledExceptionMode.CatchException);

    int zero = 0;
    int i = 10 / zero;
}
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92