Today , i came across this code

class Something

public static void main(String[] args)

    System.out.println("In try block");
    return ;
    catch(Exception e){
        System.out.println("Hello World in catch!");
    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

5 Years
Discussion Span
Last Post by JamesCherrill

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???



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)

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.