In this program, we will handle a StringIndexOutOfBoundsException using try, catch block. The code that may generate an exception should be written in the try block, and the catch block is used to handle the exception and prevent program crashes.
Program/Source Code:
The source code to handle StringIndexOutOfBoundsException is given below. The given program is compiled and executed successfully.
// Java program to handle StringIndexOutOfBoundsException
public class Main {
public static void main(String[] args) {
try {
String str = "includehelp";
System.out.println("Char: " + str.charAt(str.length()));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
System.out.println("Program finished");
}
}
Output:
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 11
Program finished
Explanation:
In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program. Here, we created try and catch blocks. In the try block, the String Index Out Of Bounds Exception gets generated because we tried to access of character from the out of the bound index.
Here, we handled generated exceptions using the catch block and printed exception message.
In this program, we will handle a StringIndexOutOfBoundsException using try, catch block. The code that may generate an exception should be written in the try block, and the catch block is used to handle the exception and prevent program crashes.
Program/Source Code:
The source code to handle StringIndexOutOfBoundsException is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program. Here, we created try and catch blocks. In the try block, the String Index Out Of Bounds Exception gets generated because we tried to access of character from the out of the bound index.
Here, we handled generated exceptions using the catch block and printed exception message.