简体   繁体   English

IndexOutOfBounds异常Java字符串类charAt方法

[英]IndexOutOfBounds Exception Java String Class charAt Method

Method CharAt of the Java String class throws a StringIndexOutOfBoundsException. Java String类的CharAt方法抛出StringIndexOutOfBoundsException。 But the Java API documentation says it throws an IndexOutOfBoundsException . 但是Java API文档说它抛出IndexOutOfBoundsException I know that StringIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException . 我知道StringIndexOutOfBoundsExceptionIndexOutOfBoundsException的子类。 But is it incorrect to catch StringIndexOutOfBoundsException instead of IndexOutOfBoundsException ? 但是,捕获StringIndexOutOfBoundsException而不是IndexOutOfBoundsException是不正确的吗?

Here is the code of the charAt method 这是charAt方法的代码

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

No, it's not incorrect. 不,这是不正确的。 But you can save a few keystrokes and just use IndexOutOfBoundsException, unless you have a method that uses String indexing and eg array indexing or list indexing etc. Then you could differentiate the exception types to handle the cases differently. 但是,您可以节省一些击键,仅使用IndexOutOfBoundsException, 除非您有使用String索引和例如数组索引或列表索引等方法。然后,您可以区分异常类型以不同方式处理案例。

It is just the closest exception thrown , what is the need of having so many inbuilt Exception classes, when we can always throw/use Exception class . 这只是抛出最接近的异常 ,当我们总是可以throw/use Exception class时,有那么多内置的Exception类是需要的。

You have ArrayIndexOutOfBoundsException for Arrays, similarly StringIndexOutOfBoundsException for working on Strings etc.. 对于数组,您具有ArrayIndexOutOfBoundsException对于字符串等,您具有类似的StringIndexOutOfBoundsException

more here 这里更多

I would prefer IndexOutOfBoundsException in situations like this : 在这种情况下,我更喜欢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)

It is not wrong. 没错 It is just a design consideration. 这只是设计上的考虑。 The same applies to IOException and FileNotFoundException . IOExceptionFileNotFoundException

You should not look at a specific implementation. 您不应查看特定的实现。 The documentation says it throws IndexOutOfBoundsException , then if you want to handle this (which is not really necessary) you'd better catch that. 该文档说它抛出IndexOutOfBoundsException ,然后,如果您想处理此问题(这不是真正必要的话),则最好抓住它。

There could be different Java implementations that don't do the check and simply let the array access throw ArrayIndexOutOfBoundsException , or in the next version Oracle might decide to do that. 可能有不同的Java实现不进行检查,只是简单地让数组访问抛出ArrayIndexOutOfBoundsException ,或者在下一版本中,Oracle可能会决定这样做。

Just handling StringIndexOutOfBoundsException would couple you to a specific implementation, and not to the general contract described in the API documentation. 仅处理StringIndexOutOfBoundsException会使您耦合到特定的实现,而不是API文档中描述的常规合同。

My example above is purely hypothetical, as the documentation of StringIndexOutOfBoundsException firmly establishes that String should throw it, but as a general rule: follow the contract. 上面的示例纯粹是假设的,因为StringIndexOutOfBoundsException的文档牢固地确定String应该将其抛出,但是作为一般规则:遵循合同。

It's not incorrect since that's what the method actually throws, and since it's a RuntimeException (ie unchecked), it doesn't matter, since you don't have to catch it at all. 这不是不正确的,因为这实际上是方法抛出的内容,并且因为它是RuntimeException (即未检查的),所以没有关系,因为您根本不必捕获它。

Now, if it was a checked exception : 现在,如果这是一个检查异常:

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

Here, if you call someMethod in a try block and only catch SomeSubCheckedException , the code won't pass compilation, since, as far as the compiler is concerned, someMethod may throw an instance of SomeCheckedException which is not SomeSubCheckedException . 在这里,如果您在try块中调用someMethod并仅捕获SomeSubCheckedException ,则代码将不会通过编译,因为就编译器而言, someMethod可能会抛出SomeCheckedException的实例, SomeCheckedException该实例不是SomeSubCheckedException

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

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