To continue on the exception post from last week I did a bit more research and learnt some more. I thought that I will share that with everyone. We had some interesting conversations in our team about exception handling and the following thought came up.

.NET gives you an option to write an unhandled exception handler which can be used to catch exceptions that you did not expect in your code and hence did not handle in your catch block. These are errors in the code as you did not expect them and should fail the application. This interestingly works even if you “throw;” or “throw new Exception(..)” from within the catch block.

It will be a good pattern to use this to log information about all unexpected exceptions in the application without introducing a “catch(Exception e)” in the code.

The sample below demonstrates the code for the exception handler. If you uncomment the throw blocks one then the handler will be invoked when the exception is thrown. Does anyone use this pattern and have benefited from it? Are there other ways to do this? Love to hear your thoughts!

 

using System;

public class Sample

{

   public static void Example()

   {

      AppDomain currentDomain = AppDomain.CurrentDomain;

      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

 

      try

      {

         throw new Exception("First Handled Exception");

      }

      catch (Exception e)

      {

         Console.WriteLine("Catch clause caught : " + e.Message);

      }

 

      try

      {

          throw new Exception("Second Handled Exception");

      }

      catch (Exception e)

      {

          Console.WriteLine("Catch clause caught : " + e.Message);

          // throw;

          // throw new Exception("Re-throw second exception", e);

      }

 

      // throw new Exception("Un-Handled Exception");

   }

 

   static void MyHandler(object sender, UnhandledExceptionEventArgs args)

   {

      Exception e = (Exception) args.ExceptionObject;

      Console.WriteLine("Exception Message: {0}", e.Message);

   }

 

   public static void Main()

   {

      Example();

   }

}