Monday, September 19, 2011

throw vs throw ex: C# .NET Exceptions

There are a couple options to raise an exception again after it has been caught. One option is to raise the exception again by using the "throw exception" keyword like below:

try
{
   ...//code that encounters an exception
}
catch (Exception ex)
{
   ...//exception handling code
   throw ex; //raise the exception again
}

The disadvantage in this way is that the original context of the exception is lost. There is no longer a meaningful call stack attached to the exception because it will contain the latest context from the newly added throw. If you plan to throw the exception in this matter you should wrap the original exception into another new more high level (application) exception. The new exception would add more high level info about the original exception.


The second option is to use the throw keyword alone with out passing the actual exception variable. This tells the .NET framework to throw the original exception without updating its context like below:

try
{
   ...//code that encounters an exception
}
catch (Exception e)
{
   ...//exception handling code
   throw; //notice the exception e is omitted
}

This way should be used when the exception is trivial enough and the code is too small to require wrapping into another exception. Again the advantage here is that you maintain the original call stack so that any user of this code can track the cause of the exception.

It's worth noting that Java is different in this aspect and using "throw ex" in Java will retain the original stack trace.