2013-10-16 53 views
8

我有疑问Exception with Inheritance为什么java ArrayIndexOutOfBound异常扩展IndexOutofBound异常不是可抛出的?

为什么

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException

然后

public class IndexOutOfBoundsException extends RuntimeException

然后

public class RuntimeException extends Exception

为什么不

public class ArrayIndexOutOfBoundsException extends Exception

为什么这个层次维持。任何指导,将是有帮助吗?

回答

7

这是为了保持有意义的层次结构,也用于分组相关的例外。另外,如果你知道什么是IndexOutOfBoundsException,并且有人给你另外一个例外,那么你可以立即从这个事实中收集信息。在这种情况下,一些涉及的对象将索引保持在一定范围内。

如果每个异常延长ExceptionRuntimeException(它的出现是否应检查或不检查),它的名字是有些模糊,你有没有线索它可能代表。

请考虑以下代码。

try { 
    for (int i = 0; i < limit; ++i) { 
     myCharArray[i] = myString.charAt(i); 
    } 
} 
catch (StringIndexOutOfBoundsException ex) { 
    // Do you need to treat string indexes differently? 
} 
catch (ArrayIndexOutOfBoundsException ex) { 
    // Perhaps you need to do something else when the problem is the array. 
} 
catch (IndexOutOfBoundsException ex) { 
    // Or maybe they can both be treated equally. 
    // Note: you'd have to remove the previous two `catch`. 
} 
1

因为ArrayIndexOutOfBoundsException亚型IndexOutOfBoundsException

9

那是因为ArrayIndexOutOfBoundsException也是IndexOutOfBoundsExceptionRuntimeException

在你的建议中,ArrayIndexOutOfBoundsException只会是Exception

所以,如果你只想赶上RuntimeException例如,ArrayIndexOutOfBoundsException将不会被捕获。

1

这就是继承进入图片的地方,并且有助于保持继承级别的清洁和专注,并且具有可扩展性的主要目标。有拐杖是错误的索引不仅在阵列,但即使在字符串等HTH

相关问题