String Index Out Of Bounds Exception Java Example Program

Syntax

try{
	//Do Something
}catch(Exception e){
	//Do something with caught exception
}


String Index Out Of Bounds Exception Example Program

public class StringIndexOutOfBoundsException {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the input text : ");
        try{
            char c = scanner.nextLine().charAt(4);
            System.out.println("The character at index 4 is : "+c);
        }catch(Exception e){
            //StringIndexOutOfBoundsException cannot be caught explicitly
            System.out.println("Caught exception : "+e.toString());
        }
    }
}


Sample Output 1

Enter the input text : 
tea
Caught exception : java.lang.StringIndexOutOfBoundsException: String index out of range: 4


Sample Output 2 

Enter the input text : 
teacher
The character at index 4 is : h