繁体   English   中英

IndexOutOfBounds异常Java字符串类charAt方法

[英]IndexOutOfBounds Exception Java String Class charAt Method

Java String类的CharAt方法抛出StringIndexOutOfBoundsException。 但是Java API文档说它抛出IndexOutOfBoundsException 我知道StringIndexOutOfBoundsExceptionIndexOutOfBoundsException的子类。 但是,捕获StringIndexOutOfBoundsException而不是IndexOutOfBoundsException是不正确的吗?

这是charAt方法的代码

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

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

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

对于数组,您具有ArrayIndexOutOfBoundsException对于字符串等,您具有类似的StringIndexOutOfBoundsException

这里更多

在这种情况下,我更喜欢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

您不应查看特定的实现。 该文档说它抛出IndexOutOfBoundsException ,然后,如果您想处理此问题(这不是真正必要的话),则最好抓住它。

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

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

上面的示例纯粹是假设的,因为StringIndexOutOfBoundsException的文档牢固地确定String应该将其抛出,但是作为一般规则:遵循合同。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM