public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
try {
a[0] = 4;
if (i <= 0) {
int k = j/i;
} else {
System.out.println(j/i);
}
} catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
void k() {
int[] a = new int[2];
{
try {
a[4] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range");
}
}
}
}
public class Nested {
public static void main(String[] args) {
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}
}
-2
Executing finally block in code
Wrong valuejava.lang.ArithmeticException:/by zero
Executing finally block in code
out of range
out of range
每當我執行finally{}
塊下面是越來越兩次執行它寫在代碼中。不知道爲什麼會發生這種情況。我只想運行一次finally塊。 有沒有辦法在單一方法中拋出多個異常?
因爲你說了兩次,不是嗎? – Leri
而不是在構造函數中有邏輯,並有這種「問題」,你可以將邏輯移動到一個方法,所以它非常簡單... 2方法調用= 2'try {} catch {} finally {}'塊 – araknoid