Search code examples
javaarraysexceptionerror-handlingprintln

How to print out the exception error in Java


I am trying my Java program to print an error message if nothing is entered in the command prompt. The user is expected to enter two file names in the command-line in Eclipse as arguments separated by a space. So if he/she has not entered anything I want this message to appear.

My code is as follows.

public class BTextLoader {

    ConcurrentHashMap<String, String> documents = new ConcurrentHashMap<String, String>();

    public static void main(String[] args) {
        // instantiate an instance of the TextLoader class.
        B1TextLoader loader = new TextLoader();

        // map .txt and .json names to the array of strings
        String txtFile = args[0];
        String jsonFile = args[1];

        // Check if command line arguments are NOT empty and then enter the file names.
        if (args.length > 0) {

            for (int x = 0; x < args.length; x++)
                loader.LoadTextFile(args[0]);           
                loader.SaveDocumentsToJSON(args[1]);
        
        }

        // Print a message if a required file name is not provided...
        else {
            System.err.println("No valid file has been entered. Please enter the file.");
        }

    }

I do not understand why my else statement does not work? Instead of printing out my error message in the console, I am getting

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at pipeline.TextLoader.main(TextLoader.java:18)

Thank you!


Solution

  • Your if statement is asking is args.length greater than 0. When you should be asking, is args.length equal to 0.

    To do this you would use if(args.length == 0). This is because args.length cannot be less than 0, and if it is greater than 0, then it's passed your test, and your program can continue. However, if it is equal to 0, then it means no arguments were passed.

    I personally, would suggest you use a try catch block.

    try{
      B1TextLoader loader = new TextLoader();
      String txtFile = args[0];
      String jsonFile = args[1];
    
    } catch (Exception e){
       System.err.println("Error: No valid file has been entered");
       System.exit(1);
    }
    
    for (int x = 0; x < args.length; x++){
          loader.LoadTextFile(args[0]);           
          loader.SaveDocumentsToJSON(args[1]);
    }