Java – throw exceptions in finally and catch blocks
There is a problem with the exception thrown in catch. Finally, stop:
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 the above code many times It gives me different output every 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
Solution
All you see is writing to system Out and system Competitive conditions between errs You explicitly call system out. Print 1, then 3, then 4, then 2, and the exception is thrown and automatically dumped to system err. So every output you get is "1342", which has an exception stack trace
The actual execution process is the same in each case - it just outputs different To prove this, you can wrap the whole main method in a try / catch block that writes exceptions to system Out, which will now work with all existing systems Out calls synchronization, and there is no race condition