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