Related Topics

JAVA Programming
String str = "hello";
char ch = str.charAt(5); // This will throw a StringIndexOutOfBoundsException
In this example, we are trying to access the character at index 5 of the String str
, which does not exist. Therefore, a StringIndexOutOfBoundsException
will be thrown.
This exception can also be thrown by methods that take a starting and ending index as parameters, such as the substring
method of the String
class. If the specified indices are out of bounds, a StringIndexOutOfBoundsException
will be thrown.
try {
// Attempt to call a method that doesn't exist
Class myClass = MyClass.class;
Method myMethod = myClass.getMethod("nonExistentMethod");
} catch (NoSuchMethodException e) {
// Handle the exception
System.out.println("Method not found: " + e.getMessage());
}
In this example, the getMethod()
method of the Class
class is called with the name of a non-existent method. When the JVM is unable to find the requested method, it throws a NoSuchMethodException
, which is caught by the catch
block and handled accordingly.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.