Internal implementation of exception handling

Today, when I write a piece of code as follows:

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

I suddenly understand that

 catch (Exception e) { ... } 
Operator

very similar to function declaration. And I vaguely remembered that exception handling is related to the progress / manipulation of the stack.

So, what is the exception handling code compiled into? I have the feeling that the above code is just a special / convenient syntax to facilitate our coding, but in fact, maybe our code ends up in an automatic generated exception handling function? I hope I get it.

+8
c # exception exception-handling
source share
2 answers

Luckily for you, CLR architect Chris Brumme has written a long explanation of how exception handling works in the CLR. Now it was written eight years ago, and some 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

+9
source share

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

In principle, they seem to be like functions, but not quite. They are not called, in fact, they do not have a separate stack frame (or a separate stack, for that matter); instead, the current function stack stack is used. This is why you can access local variables.

If you want to see what it compiles, you can use ILDasm.exe to decompile the assembly with exception blocks (so make a sample program and decompile it). Alternatively, use RedGate Reflector for better decompilation.

If IL is not enough, you can get the assembled assembly by running your program in debug mode in Visual Studio, setting a breakpoint in your method, and then when this breakpoint is deleted, the disassembly tab / window opens from the Debug menu.

+6
source share

All Articles