Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Throw Trap

Often, in exception handling, we would need to re-throw an exception caught in the catch block, after doing some operation (logging the exception, for instance). But, we  generally make the mistake of providing the exception argument in the throw expression. The problem is that, in this case, we might lose the original call stack. Here's a small snippet to give you the idea:

static void exA()
{
   
try
   
{
        exB();
   }
   
catch(Exception ex)
   {
        
//Watch out!
     //throw ex;
    
     //Better
     
throw;
   }  
}
 
static void exB()
{
   
throw new Exception("New Exception"); 
}

static void Main(string[] args) 
{
   
try
   
{
        exA();
   }
   
catch(Exception e) 
   {
     Console.WriteLine(e.StackTrace);
   }
}

If we were to do a throw ex in the above snippet, then we would have the following stacktrace.  Note that we have lost exB() in the stack trace.

exA()
Main(String[] args)

If we were to just re-throw the exception, then we would have got the entire stack trace

exB()
exA()
Main(String[] args)

For more information refer to the C# Language Specification and Lance Hunt's C# Coding Guidelines for .NET.

Posted: Oct 24 2004, 06:55 PM by Manoj G | with 1 comment(s)
Filed under:

Comments

Ulf said:

Hi,

I have a question or need to get some thing confirmed because I'm a bit unsure about this.

Looking at Lance Hunts guideline paragraph 4.4 the example says

// Bad!

catch(Exception ex)

{

Log(ex);

throw ex;

}

// Good!

catch(Exception)

{

Log(ex);

throw;

}

As I understand it is not possible to do as in the good example, since ex is not declared. Or am I wrong?

If I do the good example as you do it, it seems that I get the same result. I'm I right about that?

// Good! (Modified)

catch(Exception ex)

{

Log(ex);

throw;

}

# March 12, 2008 11:07 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)