Home Dev Blog Rethrowing Exceptions in .Net
Rethrowing Exceptions in .Net Print

Look at the following C# code:

 try
 {
     //some code where you call another class
     //or another function and it raises an exception
  }
 catch (SomeException e)
 {
     //Log the exception, or something
     throw e;
 }

Looks OK? In fact, using throw e in the last line will destroy the stack of the exception; the information about where it was originally raised (in the other class or function) will have vanished.

 

Rather, use the following:

 try
 {
     //some code where you call another class
     //or another function and it raises an exception
  }
 catch (SomeException e)
 {
     //Log the exception, or something
     throw;
 }

This rethrows the exception but preserves the original context of the exception and the stack.

Last Updated on Monday, 22 February 2010 12:54
 
Copyright © 2010 CIT Systems Ltd. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.