Saturday, March 05, 2011

To Throw or to Rethrow :)

When you need to bubble up the exception there are few ways you can do it.
Consider a Method Foo throws some exception.
        private static void Foo()
        {
            //
            // Some nasty behavior.
            //
            throw new Exception();
        }

I.     Throw with parameter
      private static void ThrowWithVariable()
        {
            try
            {
                Foo();
            }
            catch (Exception ex)
            {

                //do something and bubble up
                throw ex;
            }
        }
           
             Output:
Message: Exception of type 'System.Exception' was thrown.
StackTrace: at ConsoleApplicationThrow.Ex.ThrowWithVariable() in H:\Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 102
at ConsoleApplicationThrow.Ex.Main() in H:\Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 20

            II.   Throw without parameter 
         private static void ThrowWithoutVariable()
        {
            try
            {
                Foo();
            }
            catch
            {
                //do something and bubble up
                throw;
            }
        }

                Output:
Message: Exception of type 'System.Exception' was thrown.
StackTrace:   at ConsoleApplicationThrow.Ex.Foo() in H:\\Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 67
at ConsoleApplicationThrow.Ex.ThrowWithoutVariable() in H:\ Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 90
at ConsoleApplicationThrow.Ex.Main() in H:\ Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 35

III. Throw after wrapping in new exception  
        private static void ThrowWithNewException()
        {
            try
            {
                Foo();
            }
            catch (Exception ex)
            {
                //do something and bubble up
                throw new Exception("Some useful info", ex);
            }
        }

Output:
Message: Some useful info
StackTrace: at ConsoleApplicationThrow.Ex.ThrowWithNewException() in H:\Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 78
at ConsoleApplicationThrow.Ex.Main() in H:\Study\ConsoleApplicationThrow\ConsoleApplicationThrow\Program.cs:line 50

 Conclusions:
1.       When the exceptions are needed to be bubbled up use “throw without parameter” instead of “throw with parameter”. This will ensure you will not lose out on actual line of code throwing exception.
2.       Exception to this is when you would be adding some extra information and would be throwing new exception.

Few other related links:

No comments: