简体   繁体   中英

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!

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

You want to do stuff if there are input arguments, and other stuff if there are not input arguments. Right now, your code is mixing those two together (and as a result, it does not function correctly).

Here's a simpler approach that checks for your initial requirement up front (expect two arguments) and skips everything else if those arguments are not present.

if (args.length < 2) {

    // if missing expected two arguments, eject right away
    System.err.println("No valid file has been entered. Please enter the file.");

} else {

    // ok, you have 2 (or possibly more) arguments
    // go ahead and do everything else here

    B1TextLoader loader = new TextLoader();
    String txtFile = args[0];
    String jsonFile = args[1];

    for (int x = 0; x < args.length; x++) {    // remove this, it isn't needed
        loader.LoadTextFile(args[0]);           
        loader.SaveDocumentsToJSON(args[1]);
    }                                          // remove this, too
}

Note: I added braces around the two lines after the "for" loop. The indendation makes it look like you want both "loader" lines to run inside the loop, but without braces that would not be the case.

EDIT: I added comment lines to the code that the "for" loop should be removed.

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