1
考慮以下類與方法:a()調用b(),然後調用c()。重新拋出異常時調用序列的差異
public class ReThrower {
public static void a(int a1){
try{
a1+=1;
b(a1);
}
catch(ArithmeticException e){
System.out.println("Exception caught at a");
throw e;
}
}
public static void b(int b1){
try{
b1+=1;
c(b1);
}
catch(ArithmeticException e){
System.out.println("Exception caught at b");
throw e;
}
}
public static void c(int c1){
int zero=0,result;
try{
result=c1/zero;
}
catch(ArithmeticException e){
System.out.println("Exception caught at c");
e.printStackTrace();
throw e;
}
}
public static void main(String[] args) {
a(5);
}
}
當我跑上面的代碼中,初始輸出接收到的是:
Exception caught at c
java.lang.ArithmeticException:/by zero
Exception caught at b
Exception caught at a
at com.atul.security.ReThrower.c(ReThrower.java:31)
at com.atul.security.ReThrower.b(ReThrower.java:20)
at com.atul.security.ReThrower.a(ReThrower.java:10)
at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException:/by zero
at com.atul.security.ReThrower.c(ReThrower.java:31)
at com.atul.security.ReThrower.b(ReThrower.java:20)
at com.atul.security.ReThrower.a(ReThrower.java:10)
at com.atul.security.ReThrower.main(ReThrower.java:46)
即使在與c()打印的完整堆棧跟蹤,包括在B()和所述系統輸出()已經已經執行。 然而,當我再次運行它,輸出改變這樣的:
Exception caught at c
Exception caught at b
Exception caught at a
java.lang.ArithmeticException:/by zero
at com.atul.security.ReThrower.c(ReThrower.java:31)
at com.atul.security.ReThrower.b(ReThrower.java:20)
at com.atul.security.ReThrower.a(ReThrower.java:10)
at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException:/by zero
at com.atul.security.ReThrower.c(ReThrower.java:31)
at com.atul.security.ReThrower.b(ReThrower.java:20)
at com.atul.security.ReThrower.a(ReThrower.java:10)
at com.atul.security.ReThrower.main(ReThrower.java:46)
鑑於這是單線程的,爲什麼會出現在多個運行行爲的改變?
但它不是多線程 - 當然這種交錯將是確定性的? – selig
看不出原因;流緩衝是異步的。 @assylias在這裏是正確的。 – Bathsheba