3 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
但是我希望讓它完成循環(huán)而不是在錯(cuò)誤被捕獲時(shí)停止。
好的。然后將try和移動(dòng)catch 到循環(huán)中。
for (int i = 0; i < 6; i++) {
try {
testInst = new myClass(sizes[i]);
System.out.println("New example size " + testInst.size);
} catch (NegativeArraySizeException e) {
System.out.println("Must not be a negative.");
}
}

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
首先指定程序中的位置可以拋出異常。其次指定如何處理異常,例如指定您要拋出該異常還是只寫日志并繼續(xù)執(zhí)行。第三,您指定何時(shí)處理異常。在您的代碼中,try-catch 可以在構(gòu)造函數(shù)中,也可以在循環(huán)和下面的代碼中,以達(dá)到您的目標(biāo)。testInst = new myClass(sizes[i]);

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
只需將 try-catch 塊放入循環(huán)中即可。這樣,如果拋出錯(cuò)誤,您可以處理它并繼續(xù)循環(huán)。這是代碼:
public class myClass {
int[] table;
int size;
public myClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
myClass testInst;
for (int i = 0; i < 6; i++) {
try {
testInst = new myClass(sizes[i]);
System.out.println("New example size " + testInst.size);
} catch(NegativeArraySizeException e) {
System.out.println("Must not be a negative.");
continue;
}
}
}
}
添加回答
舉報(bào)