Wednesday, October 19, 2011

Re-throwing exceptions Throw Vs Throw ex


Most of us use exception handling very frequently .we generally use try catch finally for handling exceptions.We are often mislead due to bad rethrow of exceptions.
The following snippet shows a bad rethrow
using System;

namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                callerFunc();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();

        }

        static void  callerFunc( )
        {

            try
            {
                calleeFunc();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        static void calleeFunc()
        {

            try
            {
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ex ;
            }


        }

    }

The result of this code is shown below


The information here is totally misleading as it only gives a partial idea of the total stacktrace of the program. The stacktrace is not preserved.

The Solution is to never use Throw ex, instead use only Throw. The following code preserves the stacktrace of the code.

using System;

namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                callerFunc();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();

        }

        static void  callerFunc( )
        {

            try
            {
                calleeFunc();

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        static void calleeFunc()
        {

            try
            {
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {
                throw ;
            }


        }

    }
}


The output of this code preserves the stackTrace totally to get the exact location of the exception.


No comments: