Index Out of Bound Exception are the Unchecked Exception that occurs at run-time errors. This arises because of invalid parameter passed to a method in a code. The java Compiler does not check the error during the compilation of a program. Index Out of Bound Exception Occurs when a programmer try to access an element of beyond the storage capacity of the index.
Index Out of Bound Exception are further classified into two types-
1.Array Index Out of Bound Exception-These are the exception arises when a programmer tries to access an element beyond the capacity of index of the array. This exception are seen at run-time rather than the compile time. This causes the program to crash at run-time.Inorder to overcome this problem, you write the exceptional -handler that process the program. Now place the code in try block that cause exception in program. If exception arises in try block, you pass the control to the specific catch block preceding try block If there is no catch block, the program will terminated.
How to Handle Array Out of Bound Exception
The below example define a class 'Example', that shows out-of-bounds exceptionwhen you attempt to access an element of array with an illegal subscript. . To avoid this condition, you can write an exception handler that processes the exception and keeps your program running. Place the code that cause the exception in the try block. If there is an exception in the try block, transfer the control to the catch block. If there is no catch block the program will terminate.
public class Example
Output on the Command Prompt.
Valid indexes are 0, 1,2,3,4,5,6 or 7
End of program
2.String Index Out of Bound Exception- The String Index Out of Bound Exception is a subclass of Index out of Bound Exception. This exception is thrown when a String object detects an index out-of-range index. Usually, An string object occurs out-of-range , when the index is less than zero, or greater than or equal to the length of the string.
The above Constructor creates an string Index Out of Bounds Exception with no message associated with it.
public String Index Out of Bound Exception(int index)
The above Constructor creates an StringIndexOutOfBoundsException class with an argument indicates the illegal index associated with it.
Some of the Inherited Method
|Method||Inherited Method||Inherited Form|
|fillinStackTrace( )||Throwable Finalize ( )||Object|
|get Class||Object get Localized Message||Throwable|
|get message||Throwable Hashcode||Object|
|print stack trace ( )||Throwable print stack trace ( )||Throwable|
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial