如何使用 ArrayOutOfBoundException 打印语句

How to print a statement using ArrayOutOfBoundException

我正在尝试使用 ArrayOutOfBoundException 打印 System.out.println 语句,但我不太确定如何去做。

这是我到目前为止所做的:

public class Ex4
{
    public static void main(String[] args) {
        String text= "";

        if ( args.length <= 3 ) { 

            for (int i=0; i<args.length-1; i++) {
                text = text  + args[i];
            }

            System.out.println(text);
        }
        else if( args.length > 3 ) {
            throw new ArrayIndexOutOfBoundsException("Out of Bounds Exc. Size is 4 or more"); 
        }
    }
}

一个ArrayIndexOutOfBoundsException是一个RuntimeException,用户不应该真正看到,更好的解决方案是直接打印到System.err或者使用像[=这样的日志框架15=]:

} else if (args.length > 3) {
    System.err.println("Out of Bounds Exc. Size is 4 or more"); 
}

但是,要回答您最初的问题,要专门记录 AIOOBE,您需要捕获它:

try {

} catch (ArrayIndexOutOfBoundsException aioobe) {
    // log here...
}

但是,再次强调,捕获运行时异常不是解决问题的方法,因为它们实际上是为了表示编程错误而不是用户输入问题