亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

錯誤處理會停止程序,但是我希望程序繼續在 Java 中循環

錯誤處理會停止程序,但是我希望程序繼續在 Java 中循環

catspeake 2021-08-04 10:38:05
我有一個可以運行并捕獲錯誤的程序,但是我希望它完成循環而不是在捕獲錯誤時停止。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;        try {            for (int i = 0; i < 6; i++) {                testInst = new myClass(sizes[i]);                System.out.println("New example size " + testInst.size);            }        }catch (NegativeArraySizeException e) {            System.out.println("Must not be a negative.");        }    }}當數組大小為負時會發生錯誤,但是我如何繼續完成循環?
查看完整描述

3 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

但是我希望讓它完成循環而不是在錯誤被捕獲時停止。


好的。然后將try和移動catch 到循環中。


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.");

    }

}


查看完整回答
反對 回復 2021-08-04
?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

首先指定程序中的位置可以拋出異常。其次指定如何處理異常,例如指定您要拋出該異常還是只寫日志并繼續執行。第三,您指定何時處理異常。在您的代碼中,try-catch 可以在構造函數中,也可以在循環和下面的代碼中,以達到您的目標。testInst = new myClass(sizes[i]);


查看完整回答
反對 回復 2021-08-04
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

只需將 try-catch 塊放入循環中即可。這樣,如果拋出錯誤,您可以處理它并繼續循環。這是代碼:


    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;

                }

        }

    }

}


查看完整回答
反對 回復 2021-08-04
  • 3 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號