【问题标题】:Can we use "catch" to handle OutOfBoundsException with specific value?我们可以使用“catch”来处理具有特定值的 OutOfBoundsException 吗?
【发布时间】:2017-06-20 02:29:46
【问题描述】:

我正在学习 java 中的异常。我遇到了以下问题:

String bigstring = myscanner.nextLine();
String[] splited = bigstring.split("\\s+");
try {
    smallstring1 = splited[0];
    smallstring2 = splited[1];
    smallstring3 = splited[2];
} catch(java.lang.ArrayIndexOutOfBoundsException exc) {
    smallstring3 = null;
}

如果用户只想输入 2 个单词,这将起作用。

如果他想打一个字怎么办?

我们能否以某种方式指定冒号后出错的值?

喜欢:

java.lang.ArrayIndexOutOfBoundsException: 2

或

java.lang.ArrayIndexOutOfBoundsException: 1

我们可以在 try/catch 块中以某种方式使用(对于这个例子)这个“2”或“1”吗?

【问题讨论】:

    标签: java exception try-catch indexoutofboundsexception


    【解决方案1】:

    java.lang.ArrayIndexOutOfBoundsException 不是可恢复的异常。它传达了一个编程错误。
    因此,与其试图了解导致 catch 问题的索引,不如确保异常不会发生。

    在您的情况下,您应该在尝试获取数组的值之前检查数组的大小。

    这是一个例子:

        int arraySize = splited.length;
    
        if (arraySize == 3){
          smallstring1=splited[0];
          smallstring2=splited[1];
          smallstring3=splited[2];
        }
    
        else if (arraySize == 2){
          smallstring1=splited[0];
          smallstring2=splited[1];
        }
    
        else if (arraySize == 1){
          smallstring1=splited[0];
        }
    

    【讨论】:

      【解决方案2】:

      您可能不应该对正常的程序流程使用异常。异常通常应该是“异常的”。

      无论如何,虽然你不能这样做,但你可以在你的 catch 块中使用 if 语句。也可以查看splited.length查看数组有多大。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-23
        • 1970-01-01
        • 2022-12-20
        • 1970-01-01
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多