Wednesday, April 25, 2012

How throw works in .Net

As we all know, Exception handling plays a very important role in any developer’s life. When talking about exception handling, throw is the first thing, which comes into our mind. Today, we will see, how actually throw works.

The given code catches the exception and just throws it again, without passing any explicit Exception object. 

Now, let’s take another version of this above code:

This given code will create the object of Employee and will catch the exception and from catch block it will throw the catched exception via ex (our Exception class object).

Now question is how these two code snippets are different. For more analysis, let’s open ILDasm and drop your .EXE into it. For the first snippet, we will see something like below:

From this given image, we can see ex (Exception class object) has been defined as local variable using .local, but in the catch block, compiler changes the throw statement into rethrow. It means, instead of changing the original stack trace, compiler is just re-throwing the existing one.

Whereas, if we will look at second snippet:

Here also ex is defined as a local variable, but catch block is bit different here as compared to snippet 1.  In the catch block, compiler is loading data from location 1 (ldloc 1), which is ex (Exception object) and throws that one. And as a result, this ex will not hold all the stack trace raised earlier except the stack trace from this current state.

So, it is clear that ex override the stack trace whereas, just throw statement does not override the stack trace.

No comments:

Post a Comment