Rajaneesh
Rajaneesh

Reputation: 181

Is finally block will be executed in thread other than main thread?

public class Test {
    public static void main(String args[]) throws Exception{
        try{        
            System.out.print("1");
            throw new Exception("first");
        }   
        catch (Exception e) {
            System.out.print("2");
            throw new Exception("second");      
        }
        **finally**{
            System.out.print("3");
            try{
                System.out.print("4");              
            }catch (Exception e) {
                System.out.print("5");
                throw new Exception("third");
            }
            finally{
                System.out.print("6 ");             
            }
        }
    }   
}

Output at first run:

12Exception in thread "main" 346 java.lang.Exception: second
    at src.dec.TST501.main(TST501.java:11)

output at second run:

12346 Exception in thread "main" java.lang.Exception: second
    at src.dec.TST501.main(TST501.java:11)

output at third run: 1Exception in thread "main" java.lang.Exception: second 2346 at src.dec.TST501.main(TST501.java:11)

Can any one explain me how it is happening? Is the finally block will be a executed in any other thread than main?

Upvotes: 0

Views: 521

Answers (3)

user1337896
user1337896

Reputation: 1321

It's just because the System.err is slower than System.out, change to System.err, you will see 12346 Exception in thread "main" java.lang.Exception: second at Test.main(Test.java:8) all the time

Upvotes: 1

Jeremy Roman
Jeremy Roman

Reputation: 16355

The finally block is executed on the same thread. The reason the output is interleaved this way has to do with the way standard output and standard error output data.

Standard output is buffered (whereas standard error is not), so how the output is interleaved depends on when the system chooses to flush the output buffer. (Since your terminal emulator simply shows both of these streams together, you get the mixed output you observe.)

Upvotes: 9

Bhavik Ambani
Bhavik Ambani

Reputation: 6657

This is happening because your both finally block will be executed in any circumstances of the execution, whether there comes any exception or not

Upvotes: -2

Related Questions