2015-04-30 57 views
0

當我多次跑這個程序,我得到不同的輸出:不一致的輸出在java中

public class Demo { 
public static void main(String[] args) { 
    try { 
     System.out.println("try block"); 
     int a = 10/0; 
    } catch (Exception e) { 
     System.out.println("catch block"); 
     int a = 10/0; 
    } finally { 
     System.out.println("finally block"); 
     int a = 10/0; 
    } 
} 

}

首頁輸出:

Exception in thread "main" java.lang.ArithmeticException:/by zero 
    at kd.demo.Demo2.main(Demo2.java:14) 
try block 
catch block 
finally block 

第二輸出:

Exception in thread "main" try block 
catch block 
finally block 
java.lang.ArithmeticException:/by zero 
    at kd.demo.Demo2.main(Demo2.java:14) 

Thir d輸出:

Exception in thread "main" try block 
catch block 
finally block 
java.lang.ArithmeticException:/by zero 
    at kd.demo.Demo2.main(Demo2.java:14) 

當我編譯和執行這個程序多次,我得到不同的輸出。大多數時候我拿到了第三個,這不是問題。但是,我對其他輸出(第一和第二)感到困惑。

+3

第二個和第三個有什麼區別? –

回答

4

您正在寫入System.out(您的println語句)和System.err(將從finally塊中引發的未捕獲異常打印的堆棧跟蹤)。

交叉顯示在屏幕上的順序相當不確定。

您可以通過將消息發送到System.err而不是System.out來「解決」此問題。然後一切都會轉到同一個流。