Why is output every time every time? try to catch the exception code

class TestExceptions { public static void main(String[] args) throws Exception { try { System.out.println("try"); throw new Exception(); } catch(Exception e) { System.out.println("catch"); throw new RuntimeException(); } finally { System.out.println("finally"); } } } 

Below are the results when I try to run the code in eclipse several times. I still thought that whenever the last line of code from the try / catch block (which can be returned or throws a new Exception () stmt type) is completed, the finally block will be executed, but is the output different every time? Can anyone clarify whether my assumption is right or wrong?

 try catch Exception in thread "main" finally java.lang.RuntimeException at TestExceptions.main(TestExceptions.java:9) Exception in thread "main" try catch java.lang.RuntimeException at TestExceptions.main(TestExceptions.java:9) finally 
+7
java exception
source share
2 answers

This is clear because the eclipse prints error stream and output stream without proper synchronization on the console. Because of this, many people have seen problems.

Run the program on the command line, and each time you see the correct output.

+9
source share

agreeing with @Codebender, you can replace all thows exceptions and replace them with printStackTrace (); then exceptions and output will be printed in syn. EG:

  public static void main(String[] args) throws Exception { try { System.out.println("try"); throw new Exception(); } catch(Exception e) { System.out.println("catch"); e.printStackTrace(); } finally { System.out.println("finally"); } } } 
0
source share

All Articles