public class HelloWorld{
     static int a;
     public static void main(String []args){
        System.out.println("Hello World");
        HelloWorld h =new HelloWorld();
        a =;

     int foo()
     throw new Exception();
     catch(Exception e){

      return 9;


     finally{System.out.println(a);return 10;}
} }

When I ran the above code output was:
Hello World
Now i have a doubt that does the return in catch is executed first or the finally block executed first??

finally is always executed (the only exception is System.exit()). You can think of this behavior this way:

  • An exception is thrown
  • Print "catch"
  • Exception is caught and return value is set to 9
  • Finally block gets executed.Prints value of a and return value is set to 10

It is overridden by the one in finally, because finally is executed after everything else.

That's why, a rule of thumb - never return from finally. Eclipse, for example, shows a warnings for that snippet: "finally block does not complete normally"

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Quote from

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.