简体   繁体   中英

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);
}
}

The Program throws a Exception can any one tell me how to handle it. java.lang.ArrayIndexOutOfBoundsException: 0 The number of occurrence of String is 0

Please check

if ( args[1] != null ) {

}

before using args[1] like below

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

Simply catching an exception like this is a very bad thing to do.

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

That there is an exception indicates that something is wrong and the default action that happens will be to terminate the thread with the exception message and a stack trace indicating where the exception occurred.

If you catch the exception and continue as you do here, bad and unexpected things can happen in the remainder of your program. So don't catch exceptions you are not expecting.

Instead catch specific exceptions - such as ArrayIndexOutOfBoundsException - which you think might happen and take the appropriate action. Or put in a test to avoid the exception occurring, like checking that the appropriate arguments have been passed in. Never catch unexpected exceptions and continue execution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM