0

我知道这段代码在 Eclipse 中会产生一个错误,但是我如何在它出现之前捕获它

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ArgsContentCopier.main(ArgsContentCopier.java:13)

我想抓住它,然后抛出一个字符串。而不是说线程中的异常......我希望它说例如“需要两个参数”。


感谢您的帮助,我想通了!


import java.io.*;
import java.util.Scanner;

/**
   This program copies content of a file into another.
*/
public class ArgsContentCopier
{  
   public static void main(String[] args)
   {  
      if(args.length != 2) //if args array != 2 then print error
      {
            System.out.println("Error: Two args required");
      }
      else{

          String one = args[0];
          String two = args[1];
          String inFile;
          String outFile;
          Scanner in = new Scanner(System.in);

            try
            {  


                //System.out.print("Input file: ");
                    inFile = one;
                //System.out.print("Output file: ");
                    outFile = two;

                        InputStream inStream = new FileInputStream(inFile);
                        OutputStream outStream = new FileOutputStream(outFile);

                        byte[] b = new byte[1024]; //this line reads a new byte into b from 0 to 1024bytes.
                        int len; //keeps track of the len (up to the # of bytes to read)
                        while((len = inStream.read(b)) != -1) //if there is nothing else to read, returns -1
                        {
                            outStream.write(b, 0, len); //read the docs on this http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28byte[],%20int,%20int%29
                        }

                        inStream.close();
                        outStream.close();
            }
            catch (IOException exception)
            {  
                System.out.println("Error processing file: " + exception);
            }     


        }
}
}
4

1 回答 1

4

如果你不让它被扔掉,你就不需要抓住它。在访问数组之前检查数组长度以确保ArrayIndexOutOfBoundsException不会被抛出。

if (args.length != 2)
{
    System.out.println("Two args required.");
    return;
}
// Now access args[0] and args[1]
于 2013-10-01T18:28:46.587 回答