簡體   English   中英

如何在java中使用try和catch塊

[英]how to use try and catch block in java

我正在使用 java 並且我有一個包含一些數字的文件。

1 2

3 4

我想讀取這個文件並將它存儲在一個二維數組中。 但也可能有字母或雙打,在這種情況下,我想在 try/catch 塊中打印錯誤。 下面是我的代碼,當它找到一個字母或雙倍時會產生一個錯誤。

1 2.3

一個 4

while (sc.hasNextLine()) {
    for (int y = 0; y < a.length; y++) {
        for (int x = 0; x < a[y].length; x++) {
            a[y][x] = sc.nextInt();
        }
    }
}

我想在 try/catch 塊中檢查的另一個錯誤是大小錯誤。 以下是此輸入的示例。 你可以看到它不適合二維數組。 在這種情況下,我想在 try/catch 塊中打印錯誤

1 2 3

4 5

您可以連接兩個 catch 塊。 您需要使用InputMismatchException來了解您正在檢索的值是否為 int 和ArrayIndexOutOfBoundsException以查看您是否嘗試訪問錯誤大小的數組:

while (sc.hasNextLine()) {
    for (int y = 0; y < a.length; y++) {
        for (int x = 0; x < a[y].length; x++) {
           try{
               a[y][x] = sc.nextInt();
           }catch(InputMismatchException ex){
               System.out.println("The format of the number it's not correct");
           }catch(ArrayIndexOutOfBoundsException ex){
               System.out.println("You are trying to access to a wrong index of the array");
           }

        }
    }
}

try/catch 塊用於異常處理。異常和錯誤是兩件不同的事情。異常是程序員/用戶不需要的任何結果,而不是錯誤。

易發生異常的代碼集寫在 try 塊中,異常的處理在 catch 塊內通過編寫適當的 catch 子句完成。 當在 try 塊對象內的任何語句中發生異常時,將生成該異常的執行控制,並將執行控制指向匹配異常的相應 catch 塊,即匹配參數與生成的異常對象的參數。

while (sc.hasNextLine()) {
                for (int y = 0; y < a.length; y++) {
                    for (int x = 0; x < a[y].length; x++) {
                        try{
                              a[y][x] = sc.nextInt();
                           }
                        catch(Exception e){
                             e.printStackTrace();
                        }
                    }
                }
            }

我已經編寫了通用 catch 塊,它可以捕獲異常類型的對象,即異常層次結構中最頂層的類。在您的場景中,異常名稱是 NumberFormatException 和 ArrayIndexOutOfBound 用於無效數組大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM