Covering your back – Exception handling

It is no doubt a must to handle exception properly and to log them as you do. However the reality that sometimes you fail to handle all exceptions and if you are dealing with a large code base as I usually do it may not be that easy to fix all the loop holes in your exception handling.

If you live in this ‘real’ world as I assume you do then this post if for you. It is a good idea to ensure that you deal with all unhandled exceptions in all app domains, deal with unobserved task exceptions and log all exception be they handled or not. Below I have some code samples with comments on how to do this. This however is no passport to then go about being reckless and not implementing proper exception handling throughout your application.

        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomainOnFirstChanceException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
            TaskScheduler.UnobservedTaskException+=TaskSchedulerOnUnobservedTaskException;
        }

        private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            //Do the usual you would have if this exception were handled - offcourse always log your exceptions
            //Optionally filter through the exceptions to decide whether to show a message to the user and whether to shutdown the application immediatelly
            //Keep in mind when this happens you cannot be sure that the exception previously happened as this is triggered by the finalizer thread on removing 
            //the task from memory not when something went wrong
        }

        private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
        {
            //Do the usual you would have if this exception were handled - offcourse always log your exceptions
            //At this point the application will have to be shutdown, do the user some courtesy of showing some message
        }

        private static void CurrentDomainOnFirstChanceException(object sender, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
        {
            //Being here means an exception has been thrown by managed code and the stack trace has not yet been searched for a handler
            //Please do not modify the exception here as a handler could be found
            //A good reason to handle this event is to simply log all exceptions whether they are handled or not
        }