2013-10-16 9 views
8

私はException with Inheritanceの疑いがあります。java ArrayIndexOutOfBound例外がThrowableではないIndexOutofBound例外を拡張するのはなぜですか?

なぜ

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException

、その後

public class IndexOutOfBoundsException extends RuntimeException

、その後

public class RuntimeException extends Exception

なぜこの階層は維持されているのはなぜ

public class ArrayIndexOutOfBoundsException extends Exception

...どれガイダンスが役に立つでしょうか?

答えて

7

これは理にかなった階層を維持することを目的としており、関連する例外もグループ化します。

また、IndexOutOfBoundsExceptionが何であるかを知っていて、誰かがこれを拡張する別の例外を与えた場合、この事実だけから情報をすぐに収集することができます。この場合、関与するオブジェクトの一部は、特定の範囲内のインデックスを保持します。

例外がすべてExceptionまたは(そのオカレンスをチェックするかどうかにかかわらず)に拡張し、その名前が多少わかりにくかった場合は、それが何を表すかについての手がかりがありません。

次のコードを検討してください。

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

ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionであり、RuntimeExceptionであるからです。

あなたの提案では、ArrayIndexOutOfBoundsExceptionExceptionになります。

たとえば、RuntimeExceptionだけをキャッチする場合は、ArrayIndexOutOfBoundsExceptionはキャッチされません。

1

これは継承が画像に入り、継承のレベルをきれいにし、焦点を合わせ、拡張性の主な目標を維持するのに役立ちます。配列だけでなく文字列などでも間違ったインデックスが存在する可能性があります。HTH

関連する問題