views:

131

answers:

1

How does (throw Exception) and (return value) is implemented in a Language such as Java or C#? I want to know the mechanism how its support is included in a Language and not just the usage of try { .... } catch (Exception) {} ?

We know when we call a function i.e.

public void doSomething() { .... .... return; }

Then on the call is put on the stack and when the method returns the call to doSomething on stack pops out.

What happened in the case when return statement returns with a value say return 4; the call to doSomething() on the stack pops out and the next statement on Prog counter got processed. What happened with the returned value where it got saved and how it's utilized.

======================================================

Similarly in the case of exception throw the throw ex; statement finds on the stack the appropriate catch statement and untill it finds it, it keeps popping things outa stack... How this machenism works??

+2  A: 

Take a look at this article and see if it helps. It talks about the SEH underpinnings of the .NET (C#) exception system.

EDIT:

If you are asking "How does calling methods with parameters and return values work in something like C# and Java", then look at this article.

At a really low level (what I am thinking you are asking), When you make a call to a method, you push your params onto the stack, then run the function, then pop the return value of the stack into a register and then process off of it, like the following:

  • Return from method (assembly code)
  • pop esx - Pop value off stack and store it in the EAX register
  • jz esx A01h - If the EAX register is zero, jump to this location.

EDIT #2:

In the case of an exception, the managed framework (Java, .NET, etc.) starts to unwind the stack one step at a time looking for a "catch" or "finally" block that can handle the error. It keeps doing this until it finds some block of code that can handle it or it runs out of code and just terminates the program. To understand how all this works at a stack level depends on which managed framework you are talking about, but the first article above combined with this article will give you the deeper view.

JasonRShaver
Yes I'm asking about the low level things. Thanks I figure out more or less the same but wanted to confirm.. thanks for the answer.
S M Kamran
If this answered your question, then please mark and answer or delete the question (rather then leave it orphaned)
JasonRShaver