Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how the Try catch finally block is executed by JVM

According to Java Language Specification, Section §14.20.2

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then the finally block is executed, and then there is a choice:
    • If the finally block completes normally, then the try statement completes normally.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S

If I interpret it correctly then after execution of try block finally is invoked, But how all this works and why I got the output,

public static int TestTryFinallyBlock()  
{
    int  i =0;
    try 
    {
        i= 10; //Perform some more operation
        return i;
    }       
    finally
    {
        i = 40; 
    }
}

public static void main( String[] args )
{
    int i1 = TestTryFinallyBlock(); //Here the output was 10 not 40
}   

I want to know how this thing produced output 10.

Is that when try block is executed and return statement is encountered the output value is already pushed to stack, and then the finally block is executed

I know that return is encountered first then finally blocks runs so output is 10, but How jvm interpret or how the try finally block is handled or converted by jvm?
Is that jvm uses GOTO section jump section to go to finally section or the stack is already maintained?

like image 388
dbw Avatar asked Nov 26 '25 02:11

dbw


1 Answers

After a little search and seeing what byte codes were generated, I found that actually there are no finally blocks as it seems and no jump or goto statements generated by JVM.
The above code is translated something as (if I interpret byte code correctly, If I am wrong please do correct me)

public static int TestTryFinallyBlock()  
{
  int returnValue; //A temporary return variable
  try
  {
     int  i = 0;     
     i = 10; 
     returnValue = i; 
     i = 40; 
     return returnValue;    
  }
  catch (RuntimeException e)
  {
       i = 40; //finally section code id copied here too
       throw e;
  }
}

Point to Note: If 'i' would have been a reference to a mutable class object and the contents of the object were changed in the finally block, then those changes would have been reflected in the returned value too.

like image 58
dbw Avatar answered Nov 28 '25 15:11

dbw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!