簡體   English   中英

數組索引越界異常如何在以下程序中處理?

[英]Array Index Out Of Bounds Exception how to handle it in the following program?

import java.util.*;
import java.io.*;
public class search {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner x = null;
        String k;
        int c= 0;
        try{
                 x =new Scanner( new BufferedReader (new FileReader("hh.txt"))); 
        while(x.hasNext()){
             k = x.next();
            if(k.equals(args[1]))
             {
               c++; 
             }
        }
        }catch(Exception ex){
            System.out.println(ex.toString());
        }
System.out.println("The number of occurrence of String is "+c);
}
}

程序拋出異常 誰能告訴我如何處理它。 java.lang.ArrayIndexOutOfBoundsException: 0 String 出現次數為 0

請檢查

if ( args[1] != null ) {

}

在使用 args[1] 之前,如下所示

if ( args[1] != null ) {
     if ( k.equals(args[1]) ) {
           c++; 
     }
}

簡單地捕捉這樣的異常是一件非常糟糕的事情。

   } catch(Exception ex){
        System.out.println(ex.toString());
   }

有異常表明出現了問題,發生的默認操作是使用異常消息和堆棧跟蹤終止線程,指示異常發生的位置。

如果您捕獲異常並繼續執行此處操作,則程序的其余部分可能會發生不良和意外的事情。 所以不要捕捉你沒有預料到的異常。

而是捕獲您認為可能發生的特定異常 - 例如 ArrayIndexOutOfBoundsException - 並采取適當的措施。 或者進行測試以避免異常發生,例如檢查是否已傳入適當的參數。永遠不要捕獲意外異常並繼續執行

暫無
暫無

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

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