have question on exception thrown in catch and finally block:
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print(1);
q();
}
catch (Exception i) {
throw new MyExc2();
}
finally {
System.out.print(2);
throw new MyExc1();
}
}
static void q() throws Exception {
try {
throw new MyExc1();
}
catch (Exception y) {
System.out.print(3);
}
finally {
System.out.print(4);
throw new Exception();
}
}
}
I have tried to execute above code more than one time. It gives me different outputs each time.
output 1: 1Exception in thread "main" 342test.MyExc1
at test.C1.main(C1.java:18)
output 2: 1342Exception in thread "main" test.MyExc1
at test.C1.main(C1.java:18)
output 3: 1Exception in thread "main" test.MyExc1
342 at test.C1.main(C1.java:18)
output4: 1Exception in thread "main" 34test.MyExc1
2 at test.C1.main(C1.java:18)
Please explain.
All you're seeing is a race condition between writing to System.out
and System.err
. You're explicitly calling System.out.print
with 1, then 3, then 4, then 2, and the exception is being thrown and dumped to System.err
automatically. So every output you've got is "1342" with the exception stack trace somewhere in there.
The actual execution flow is the same in every case - it's only the output which is different. To prove that, you could wrap your whole main method in a try
/catch
block which wrote the exception to System.out
, at which point it would be synchronized with all the existing System.out
calls, and there'd be no race condition.
See more on this question at Stackoverflow