Today , i came across this code

class Something
{

public static void main(String[] args)
{

   try
  {
    System.out.println("In try block");
    return ;
    }
    catch(Exception e){
        System.out.println("Hello World in catch!");
    }
    finally
    {
    System.out.println("Hello World in finally!");
    }

}
}

Now can anyone tell me the output with reason plz... ( i know the output but i want to hear from one of you with explanation .I will get back to this thread once anyone replies with answer.)

I will ask my doubt once anyone gives the answer

If you know the answer then please ask your actual question. Are you having trouble understanding finally blocks? We don't have time to waste playing games.

lol...instead of typing that whole sentence. you must have given the answer.

Anyway , why the hell is that return statement will not return as soon as it encounters .
Why that finally is executing. I know finallky will execute irrespective of the exception but "return" should immediately return the value. why the control is going to finally again.

Its like

if i write System.exit(0); instead of that return , then the finally will execute???

haha..

looks like i should create my own programming language so that whatever i create is rule.
Otherwise we should get convinced by whatever we learn.

System.exit(0) is one of a very small list of things that stop the JVM, thus preventing the finally from executing. Otherwize, a finally clause will always be executed. That's how the language is defined.

A finally clause ensures that the finally block is executed after the try block
and any catch block that might be executed, no matter how control leaves the try
block or catch block.

Java Language Specification Section 14.20 (my emphasis)

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.