Exception Handling - Don't clear the stack trace !

Akiii
Posted by Akiii under Error and Solution category on | Points: 40 | Views : 6848
We all know why we need to write try-catch block , but there are some best practices to follow while writing your code in a try-catch block. It results in getting a clean code and a discrete error handling message.

For example, we generally write try-catch block as follows :-

try
{
// Some code that throws an exception
}
catch (Exception ex)
{
// some code that handles the exception
throw ex;
}


Never code like that because you are re-throwing a new exception and clearing the stack trace. If you dont understand what i am saying, try running "RUN CODE ANALYSIS ON WEBSITE" feature from build menu in VS 2010 . It will show you an error like :-


Warning 89 CA2200 : Microsoft.Usage : '***' rethrows a caught exception and specifies it explicitly as an argument. Use 'throw' without an argument instead, in order to preserve the stack location where the exception was initially raised.


So how to write the above try-catch block ? Here's an example for you,

try
{
// Some code that throws an exception
}
catch (Exception ex)
{
// some code that handles the exception
throw;
}


What is new with the above code ? Instead of "throw ex;" , which will throw a new exception and clear the stack trace, we have simply written "throw;" . If you don't specify the exception, the throw statement will simply re-throw the very same exception the catch statement caught. This will keep your stack trace intact, but still allows you to put code in your catch blocks. And it abides to the best practice of exception handling !


I hope it will help you....

Thanks and Regards
Akiii

Comments or Responses

Login to post response