【问题标题】:How to print a statement using ArrayOutOfBoundException如何使用 ArrayOutOfBoundException 打印语句
【发布时间】:2015-05-08 09:15:22
【问题描述】:

我正在尝试使用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"); 
        }
    }
}

【问题讨论】:

  • 你想达到什么目的?
  • 如果你想调用System.out.println,就这样做 - 你为什么要抛出异常呢?
  • 这个问题来自我过去的一篇试卷,它要求使用该例外来专门打印声明,否则我会做你提到的。谢谢
  • 这对我来说似乎是一个荒谬的问题。我建议你和你的导师(或其他任何人)提出这个问题,以检查你将参加的任何考试是否可能包含这些奇怪的东西。

标签: java oop exception indexoutofboundsexception


【解决方案1】:

ArrayIndexOutOfBoundsExceptionRuntimeException,用户不应该真正看到,更好的解决方案是直接打印到System.err 或使用类似log4j 的日志框架:

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

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

try {

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

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

【讨论】:

    最近更新 更多