有没有办法设置一个 try 并捕获 ArrayIndexOutOfBound 异常来检查数组大小是否大于 3? 例如,如果参数数组 args[] 包含超过 3 个值,那么我希望异常显示错误。
到目前为止,这是我的代码:
public static void main (String[] args){
try {
args[4] = "four";
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
}
最佳答案
您可以使用args.length
获取数组中元素的数量。
关于java - 为数组长度设置 ArrayIndexOutOfBound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29782397/