JVM / Java / Exceptions / Common Runtime Exceptions
1. ArrayIndexOutOfBoundsException
Thrown when accessing an array index that's negative or >= the array's length -- a classic off-by-one bug, especially with loops using <= instead of < against array.length. Unlike a List, an array has no bounds-checked alternative like get(); the index is always used directly.
class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
for (int i = 0; i <= numbers.length; i++) {
}
}
}
2. ClassCastException
Thrown when casting an object to a type it isn't actually an instance of at runtime -- the compiler allows the cast syntactically if there's a valid inheritance relationship, but the actual runtime type is checked when the cast executes. Pattern matching for instanceof (see Versions / Java 17) avoids this by combining the check and cast.
class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = "a string";
Object no = 2;
if (no instanceof Integer) {
System.out.println(no);
}
}
}
3. NumberFormatException
Thrown by Integer.parseInt(), Double.parseDouble(), and similar methods when the input string isn't a valid number -- extra whitespace, letters, or an empty string all trigger it. Since it's a RuntimeException, it's easy to forget to handle when parsing user input or data from an external source.
public class NumberFormatExceptionExample {
public static void main(String[] args) {
int n = Integer.parseInt("1");
System.out.println(n);
String userInput = "123 ";
try {
int safe = Integer.parseInt(userInput.trim());
System.out.println(safe);
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + userInput);
}
}
}