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


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

     System.out.println("catch");
      return 9;

     }


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

When I ran the above code output was:
Hello World
catch
0
10
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"
http://weblogs.java.net/blog/staufferjames/archive/2007/06/_dont_return_in.html

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 http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Be a part of the DaniWeb community

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