How is (throw Exception) and (return value) implemented in a language such as Java or C#? I want to know the mechanism of 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 happens in a case where the 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 did it get saved and how is it utilized?
Similarly in the case of an exception throw, the throw ex; statement finds on the stack the appropriate catch statement, and until it finds it, it keeps popping things out of the stack… How does this mechanism work?
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:
pop esx– Pop value off stack and store it in the EAX registerjz 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.