以下是我的簡單測驗代碼:
class Scratch {
public static void main(String[] args){
try {
System.out.println("Line 1")。
throw new RuntimeException();
} catch (RuntimeException e) {
e.printStackTrace()。
} finally {
System.out.println("Line 2")。
}
}
}
運行后,我會得到這樣的結果:
行 1
第2行
java.lang.RuntimeException
at Scratch.main(scratch_4.java:5)
行程結束,退出代碼0。
我以為 "final "代碼必須在最后執行,但它沒有。 這是什么原因呢?
uj5u.com熱心網友回復:
默認情況下,printStackTrace會列印到System.err,而你是寫到System.out。因此,你正在向兩個不同的流寫入,在你的特定情況下,看起來涉及到的緩沖已經將輸出順序與實際執行順序對調了。
如果你寫到一個單一的流(例如,使用 System.err.println 或者呼叫 e.printStackTrace(System.out))或者改變你的 catch 塊,像你其他行那樣只寫到 System.out,你會看到 try => catch => finally 的順序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/320017.html
標籤:
