The Correct Way to Re-Throw An Exception – .Net Tip
Posted by robkraft on March 6, 2013
When catching and re-throwing an exception, you should include the original exception as a 2nd parameter. Including the original exception may provide a deeper stack trace that will assist you with solving the exception.
In the code above, if an error occurs in methodWithoutCatch(), the call stack returned will show “methodWithTryCatch” as the deepest method in the stack.
System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object. at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 34 at WindowsFormsApplication6.Form1.button1_Click
However, if you include the original exception in the throw as shown in the second throw example, then the call stack returned will show “methodWithoutCatch” as the deepest method in the stack.
System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object. ---> System.NullReferenceException: Object reference not set to an instance of an object. at WindowsFormsApplication6.Form1.methodWithoutCatch(String z) in ...\Form1.cs:line 40 at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 29 --- End of inner exception stack trace --- at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 35 at WindowsFormsApplication6.Form1.button1_Click
Including the original exception as the second parameter of your new exception provides you with a better call stack. In this example, it allows you to determine that the error occurred in the methodWithoutCatch method. In the first case, you are left wondering if the methodWithTryCatch really caused the error, or if one of the three methods it called (method1, methodWithoutCatch, or method3) caused the error.
Software Development Company in UK said
This is one of the best blogs I have read.