java - 如何捕获 ArrayIndexOutOfBoundsException?

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


        }
}
}

最佳答案

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

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

关于java - 如何捕获 ArrayIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123285/

相关文章:

java - (PDFBox)java.awt.print.PrinterException : Printer is not accepting job

java - 安装插件时 ADT 恢复为标准 Eclipse

java - 'synchronized' 真的只是语法糖吗?

java - 什么时候在 Java 中必须有默认构造函数和参数化构造函数?

java - 带有比较器的Android排序 ListView 不起作用

java - QueryDSL 从子查询中选择带有别名的值

java - 如何向已经扩展另一个的类添加可重用逻辑?

java - 返回指定用户提交的所有更改列表 - Perforce Java API

java - 批量发布Kafka对象

java - 转义序列未按预期工作