开发者

The internal implementation of exception handling

Today, when I write a piece of code like this:

try
{
   ...
}
catch (Exception e)
{
   ...
}

I suddenly realize that the

catch (Exception e)
{
  ...
}

statement is so much like a开发者_运维知识库 function declaration. And I vaguely remembered that the exception handling involves some kind of stack walking/manipulation.

So, what exactly is the above exception handling code compiled into? I have the feeling that the above code is just a special/convenient syntax to ease our coding, but in fact, maybe our code is wrapped into an auto-generated exception handling function? I hope I made myself clear.


Fortunately for you CLR architect Chris Brumme wrote a long explanation of how exception handling works in the CLR. Now, this was written eight years ago and a few of the details are slightly different today, but this should at least give you a good start.

http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx


This is a good place to start: http://msdn.microsoft.com/en-us/library/5b2yeyab.aspx#how_the_runtime_manages_exceptions

Basically, they are kind of like functions, but not really. They aren't called, per se, they have no separate stack frame (or separate stack, for that matter), using the current function's stack frame instead. That's why you can access local variables.

If you want to see what it compiles into, you can use ILDasm.exe to decompile an assembly that has exception blocks (so make a sample program and decompile it). Alternatively, use RedGate's Reflector for a better decompiling experience.

If the IL isn't enough, you can get at the generated assembly by running your program in debug mode in Visual Studio, setting a breakpoint in your method and then when that breakpoint is hit, opening the disassembly tab/window from the Debug menu.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜