Geeks With Blogs
Rahul Anand's Blog If my mind can conceive it, and my heart can believe it, I know I can achieve it.

I just wanted to share few design considerations on exception handling I learnt a few days back.

 

One very important point is whenever you re-throw an exception do what you really want to do. What I mean is there are different ways to re-throw an already caught exception:

 

You can either write:

throw ex;

Or, just write

                throw;

 

The two statements differ significantly on how the stack trace will get affected. In first case when you write “throw ex;” statement the information about your method is added onto stack trace as an origin of exception and the actual origin of exception, got cleared from the stack trace. In other case with “throw;” statement you are just re-throwing the same exception without any modification to the origin of exception in the stack trace output.

 

Not sure, but my finding is stack trace holds one entry of exception (outermost exception caught) per method entry, hence even with “throw;” statement you will lose some information about the exact point of error.

 

The following statement explains the behavior of stack trace more specifically:

 

The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception.

 

Another possible way is to recreate the exception by adding information and passing original exception as inner exception to the exception constructor. You may need this if you want to add some specific information about the exception.

 

Quoted from MSDN:

You can explicitly throw an exception using the throw statement. You can also throw a caught exception again using the throw statement. It is good coding practice to add information to an exception that is re-thrown to provide more information when debugging.

 

try

   {

                // FileNotFoundException can occur

   }

catch(FileNotFoundException e)

   {

            throw new FileNotFoundException("filename.ext not found in c:\\devdirectory",e);

   }

finally

   {

            // Cleanup

   }

 

In this case information about all exception points can be extracted by recursively getting the stack trace of inner exceptions or by implementing a while loop till the InnerException returns null. The ToString() method will also display all exceptions.

 

So, next time when you are going to re-throw some exception do what you really want to do.

 

Posted on Friday, August 5, 2005 9:43 AM C# | Back to top


Comments on this post: Exception Handling

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rahul Anand | Powered by: GeeksWithBlogs.net