如何捕获ArrayIndexOutOfBoundsException?

时间:2013-10-01 18:26:44

标签: java

我知道这段代码在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);
            }     


        }
}
}

1 个答案:

答案 0 :(得分:4)

如果不让它被抛出,你不需要抓住它。

:在访问阵列之前检查阵列长度,以确保不会抛出ArrayIndexOutOfBoundsException

if (args.length != 2)
{
    System.out.println("Two args required.");
    return;
}
// Now access args[0] and args[1]