views:

234

answers:

1

What is the order in which exception handling stack frames are pushed onto the call stack in say C#. If i have a method:

private void MyMethod() {
  try {
    DoSomething();  
  }
  catch (Exception ex)
  {
    //Handle
  }
}

Is a separate stack frame created for each exception handler as follows?

DoSomething stackframe<br/>
Exception stackframe<br/>
MyMethod stackframe<br/>

OR

DoSomething stackframe<br />
MyMethod stackframe<br />
Exception stackframe<br />

OR

something else?

+1  A: 

No, adding an exception handler doesn't add a new frame to the call stack. It just adds appropriate information so that when an exception is thrown, at each level of the call stack the framework can find the appropriate handler for that exception (if indeed there is an appropriate handler).

It's a little bit like garbage collection, where at any point of execution the GC can work out which local variables should still count as GC roots - essentially there's more to a method than the executable code itself :)

Jon Skeet
O.k. so I've misread a wikipedia article. So if DoSomething throws an exception that t doesn't handle, the call stack is unwound and each calling stack frame is examined for an exception handler? Is there anything particularly special about the way exception handler info is included in the stack frame... as opposed to say local variables?
intermension
@intermension: I don't know the details off the top of my head, but "CLR via C#" gives more information, I think.
Jon Skeet