How do I continue running after an unhandled exception?

senzacionale picture senzacionale · Oct 18, 2011 · Viewed 10.7k times · Source

I have the following code in my application that is running after an unhandled exception:

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

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;
            if (exception != null) MessageBox.Show(exception.Message + " - " + exception.StackTrace);
        }

but even if i catch unhandled exception my windows mobile application close. How to prevent closing application when i catch unhandled exception. I never want to close my app. I want to open Login form in this scenario or anything else not close app.

So what i want is to prevent closing application from unhandled exception like network is down,...

I can not use try catch in every code ....

Any idea how to prevent closing app when network is down or any other unhandled exceptions?

Answer

ctacke picture ctacke · Oct 19, 2011

You don't. When you get an AppDomain unhandled exception, your app is no longer in a stable state. Where exactly would you resume to? When you've gotten to that point, your only option, with good reason, is to exit. You could reasonably schedule yourself to run again to make sure the app comes back, but a far better idea is to actually handle the exception at its source and prevent it from being an UnhandledException.