Java 设置数组长度的ArrayIndexOutOfBound异常
有没有办法设置try-and-catch ArrayIndexOutofBond异常来检查数组大小是否大于3? 例如,如果参数数组args[]包含3个以上的值,则我希望异常显示错误 以下是我目前的代码:Java 设置数组长度的ArrayIndexOutOfBound异常,java,arrays,exception,Java,Arrays,Exception,有没有办法设置try-and-catch ArrayIndexOutofBond异常来检查数组大小是否大于3? 例如,如果参数数组args[]包含3个以上的值,则我希望异常显示错误 以下是我目前的代码: public static void main (String[] args){ try { args[4] = "four"; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array
public static void main (String[] args){
try {
args[4] = "four";
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
}
您可以使用
args.length
获取数组中的元素数。是的,可以引发异常,但我必须问为什么?数组的length属性将提供所需的内容
if ( args.length > 3 ){
//do something here
}
要引发异常,只需执行以下操作:
if (args.length > 3) {
throw new AnyExceptionYouWant();
}
您可以这样做:
if ( args.length > 3 ){
throws new ArrayIndexOutOfBoundsException("Wrong array size! (actual: " + args.length + ", max: 3)");
}
根据您在@copeg-answer中的评论, 你可以做:
if ( args.length < 3 ){
System.out.println("There I print my content, size is less than 3");
//print your content
}
else if( args.length == 3 ) { //You didnt point out what you want to do if size is equal to 3
System.out.println("Size is equal to 3");
}
else if( args.length > 3 ) {
throw new ArrayIndexOutOfBoundsException("Out of Bounds Exc. Size is 4 or more");
}
if(args.length<3){
System.out.println(“我在那里打印我的内容,大小小于3”);
//打印您的内容
}
否则,如果(args.length==3){//您没有指出在size等于3时要执行的操作
System.out.println(“大小等于3”);
}
否则如果(参数长度>3){
抛出新的ArrayIndexOutOfBoundsException(“Out-Bounds Exc.Size为4或更多”);
}
你到底想做什么?这可能有助于为您提供正确的方法。根据您的要求,上述代码可能无法工作——您的要求是,如果它的值超过3,则应该抛出异常。但是,如果的数量超过3,则赋值将有效,不会引发异常
例如,假设您传递的字符串数组是:
args = ['arg1','arg2','arg3','arg4,'arg5']
所以当你打电话的时候
arg[4]= "four";
您的呼叫将成功,新参数将导致:
args = ['arg1','arg2','arg3','arg4,'four'];
它将大于3,这是您正在寻找的,但不会抛出异常。在这种情况下,确实没有办法抛出异常并捕获异常,因为从技术上讲没有什么问题。如果您试图识别这种情况并出于某种原因抛出它,您可以执行以下操作:
public static void main (String[] args){
var maxAllowedSize = 3;
try {
args[maxAllowedSize] = "four";
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
if (args.length > maxAllowedSize) {
System.out.println("the length is too large " + args.length);
throw new Exception(); //better to make a specific Exception here
}
}
如果数组大小小于3,我试图打印数组的内容,但是如果数组大小大于3,我希望它抛出异常错误并结束。这感觉像是一个错误。您能给出一个描述您试图做什么以及为什么要做的场景吗?args[]通过命令行参数获取其值。如果为args输入的值超过3个,或者数组的长度超过3个,那么它应该抛出ArrayIndexOutOfBond异常,否则它应该打印数组内容。我理解您的意思,您希望程序执行此操作。我不明白的是你为什么要它这么做。从
main()
抛出异常是毫无意义的,因为那里没有代码来捕获它。你为什么不(比如)检查数组的大小,如果数组太长,打印一条错误消息,然后返回呢?我也不太确定,这是一个过去的考试题,我只是想弄清楚如何让它以这种方式工作。这不是更合适吗?