Friday, January 11, 2013

Difference between Throw and Throw ex in c#?

Exception bubbling means that even though you are catching the exception and doing something with it, you want that exception to "bubble" up from your code to the calling code so it has a chance to do something with that exception. This is a fairly common scenario, but it has the potential to cause some major problems when you are debugging.


Throw Ex: (Stack trace information lost)

 The original stack trace info gets overwritten. So you loose original exceptions's stack trace as only the last point from which the exception was thrown is available.
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw ex;
   9: }


In this case, the stack trace is truncated below the method that failed. What this means is that when you look at the stack trace, it will look as if the exception originated in your code. This isn't always the case, particularly if you are bubbling up a CLR generated exception (like a SqlException). This is a problem known as "breaking the stack", because you no longer have the full stack trace information. 
  
Throw: (Stack trace information preserved)

   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw;
   9: }
 Throw, on the other hand retains the stack trace with the original point of exception available.


It is always advised to use “throw” because it provides more accurate error information.




No comments:

Post a Comment