Behaviour of return statement in catch and finally

后端 未结 8 754
情歌与酒
情歌与酒 2020-11-27 11:44

Please see the following code and explain the output behavior.

public class MyFinalTest {

    public int doMethod(){
        try{
            throw new Exce         


        
相关标签:
8条回答
  • 2020-11-27 12:29

    Finally block always get executed unless and until System.exit() statement is first in finally block.

    So here in above example Exection is thrown by try statement and gets catch in catch block. There is return statement with value 5 so in stack call value 5 gets added later on finally block executed and latest return value gets added on top of the stack while returning value, stack return latest value as per stack behavior "LAST IN FIRST OUT" so It will return value as 10.

    0 讨论(0)
  • 2020-11-27 12:41

    This is an easy question if you remember the low level layout of the VM.

    1. The return value is put up the stack by the catch code.
    2. Afterwards, the finally code is executed and overwrites the value on the stack.
    3. Then, the method returns with the most up to date value (10) to be used by the caller.

    If unsure about things like this, fall back to your understanding of the underlying system (ultimately going to assembler level).

    (funny sidenote)

    0 讨论(0)
提交回复
热议问题