2

Java String 类的 CharAt 方法抛出 StringIndexOutOfBoundsException。但是 Java API 文档说它会抛出一个IndexOutOfBoundsException. 我知道那StringIndexOutOfBoundsExceptionIndexOutOfBoundsException. StringIndexOutOfBoundsException但是 catch而不是不正确IndexOutOfBoundsException吗?

这是charAt方法的代码

public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }
4

5 回答 5

1

这不是不正确的,因为这是该方法实际抛出的内容,并且因为它是RuntimeException(即未经检查的),所以没关系,因为您根本不必抓住它。

现在,如果它是一个检查异常:

public char someMethod (int index) throws SomeCheckedException {
    if (index < 0) {
        throw new SomeSubCheckedException (index); // subclass of SomeCheckedException 
    }
    return something;
}

在这里,如果您someMethod在 try 块中调用并且仅 catch SomeSubCheckedException,则代码将不会通过编译,因为就编译器而言,someMethod可能会抛出SomeCheckedExceptionis not的实例SomeSubCheckedException

于 2014-12-17T10:46:21.590 回答
0

它只是最近抛出的异常,当我们总是可以时,需要有这么多内置的异常类throw/use Exception class

你有ArrayIndexOutOfBoundsException数组,类似地StringIndexOutOfBoundsException处理字符串等。

更多在这里

于 2014-12-17T10:44:23.467 回答
0

我更喜欢IndexOutOfBoundsException这样的情况:

 public static void main(String[] args) {
    String s = "abc";
    String[] arr = new String[1];
    for (int i = 0; i < 2; i++) {
        try {
            s.charAt(5);
            System.out.println(arr[2]);
        } catch (IndexOutOfBoundsException e) { // catch both ArrayIndexOutOfBounds as well as StringIndexOutOfBounds and treat them similarly.
            System.out.println("caught");
            s = "aaaaaaaaaa";
            e.printStackTrace();

        }
    }

}

O/P :
0
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
caught
caught
    at java.lang.String.charAt(Unknown Source)
    at StaticAssign.main(Sample.java:41)
java.lang.ArrayIndexOutOfBoundsException: 2
    at StaticAssign.main(Sample.java:42)

这没有错。这只是一个设计考虑。这同样适用于IOExceptionFileNotFoundException

于 2014-12-17T10:44:38.687 回答
0

您不应该查看特定的实现。文档说它 throws IndexOutOfBoundsException,那么如果你想处理这个(这不是真的必要)你最好抓住它。

可能有不同的 Java 实现不进行检查,而只是让数组访问 throw ArrayIndexOutOfBoundsException,或者在下一个版本中,Oracle 可能会决定这样做。

仅处理StringIndexOutOfBoundsException会将您耦合到特定的实现,而不是 API 文档中描述的一般合同。

我上面的例子纯粹是假设性的,因为文档StringIndexOutOfBoundsException明确表明String应该抛出它,但作为一般规则:遵守合同。

于 2014-12-17T10:44:52.763 回答
0

不,这不是不正确的。但是您可以节省一些击键并只使用 IndexOutOfBoundsException,除非您有使用字符串索引的方法,例如数组索引或列表索引等。然后您可以区分异常类型以不同方式处理这些情况。

于 2014-12-17T10:41:40.557 回答