Reputation: 63
I have following code snippet :-
public class MyProgram {
public static void throwit(){
throw new RuntimeException();
}
public static void main(String args[]){
try {
System.out.println("Hello world ");
throwit();
System.out.println("Done with try block ");
}
finally {
System.out.println("Finally executing ");
}
}
}
As far I know, Once the program throws a RuntimeException (in the throwit() method) that is not caught, the finally block will be executed and the program will be terminated. If a method does not handle an exception, the finally block is executed before the exception is propagated.
But, the output I get have different order each time the ouptuts I got :
OUTPUT 1:-
Hello world Finally executing Exception in thread "main" java.lang.RuntimeException at tutorialspoint.A.throwit(A.java:6) at tutorialspoint.A.main(A.java:13)
OUTPUT 2:-
Hello world Exception in thread "main" java.lang.RuntimeException at tutorialspoint.A.throwit(A.java:6) at tutorialspoint.A.main(A.java:13) Finally executing
Upvotes: 2
Views: 408
Reputation: 2842
Output may be due to racing conditions in System.out
which outputs to Standard console and System.err
which outputs to error console.
Upvotes: 0
Reputation: 393771
Your understanding is correct. First the finally block is executed and then the exception is propagated.
The 2nd output is probably due to the fact that your program's output is written to System.out
and the execption's details are written to System.err
. Since both streams are re-directed to the same window, the order in which they are printed can change in different executions.
If you add the line System.setErr(System.out);
to the start of your main
method, all the output (including the errors) will be written to System.out
, and you'll always see the order as in your OUTPUT 1.
Upvotes: 3