Wednesday, 18 December 2013

Unknown

In Java, will the code in the finally block be called and run after a return statement is executed?


The answer to this question is a simple yes – the code in a finally block will take precedence over the return statement. Take a look at the code below to confirm this fact:

Code that shows finally runs after return

class SomeClass
{
    public static void main(String args[]) 
    { 
        // call the proveIt method and print the return value
     System.out.println(SomeClass.proveIt()); 
    }

    public static int proveIt()
    {
     try {  
             return 1;  
     }  
     finally {  
         System.out.println("finally block is run 
            before method returns.");
     }
    }
}
Running the code above gives us this output:

finally block is run before method returns.
1

From the output above, you can see that the finally block is executed before control is returned to the “System.out.println(SomeClass.proveIt());”  statement – which is why the “1″ is output after the “finally block is  run before method returns.” text. 

Unknown

About Blog No Baap -

Since 2016 BlogNoBaap has been bringing you the very best in all types of web resources. Posted daily, and delivered straight to your inbox each morning.

Subscribe to this Blog via Email :