health

Technology

business posts

Powered by Blogger.

Total Pageviews

Name

your name

Email *

Your Email

Message *

your message

Followers

Translate

Pages

Pages

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. 

No comments: