Unchecked exceptions in Java are subclasses of RuntimeException
, and they indicate programming logic errors that should be prevented rather than caught.
1. Common Types of Unchecked Exceptions
Exception Type | When It Occurs |
---|---|
NullPointerException | Accessing methods or fields on a null object |
ArrayIndexOutOfBoundsException | Accessing an array with an invalid index |
StringIndexOutOfBoundsException | Accessing a string character outside its range |
ArithmeticException | Performing invalid arithmetic (e.g., division by zero) |
IllegalArgumentException | Passing an invalid argument to a method |
NumberFormatException | Converting an invalid string into a number |
ClassCastException | Incorrect object casting |
UnsupportedOperationException | Trying to perform an unsupported operation |
ConcurrentModificationException | Modifying a collection while iterating over it |
2. Examples of Unchecked Exceptions
1️⃣ NullPointerException
Occurs when trying to access a method or property on a null
object.
public class NullPointerExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws NullPointerException
}
}
✅ Prevention: Always check for null
before accessing an object.
if (str != null) {
System.out.println(str.length());
}
2️⃣ ArrayIndexOutOfBoundsException
Occurs when accessing an array index that doesn’t exist.
public class ArrayIndexExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException
}
}
✅ Prevention: Check index bounds before accessing the array.
if (5 < numbers.length) {
System.out.println(numbers[5]);
} else {
System.out.println("Index out of bounds!");
}
3️⃣ StringIndexOutOfBoundsException
Occurs when accessing an invalid character index in a string.
public class StringIndexExample {
public static void main(String[] args) {
String text = "Java";
System.out.println(text.charAt(10)); // Throws StringIndexOutOfBoundsException
}
}
✅ Prevention: Validate the index before using charAt()
.
if (10 < text.length()) {
System.out.println(text.charAt(10));
}
4️⃣ ArithmeticException
Occurs when performing illegal arithmetic operations (e.g., dividing by zero).
public class ArithmeticExample {
public static void main(String[] args) {
int result = 10 / 0; // Throws ArithmeticException
}
}
✅ Prevention: Check for zero before division.
if (denominator != 0) {
System.out.println(10 / denominator);
} else {
System.out.println("Cannot divide by zero!");
}
5️⃣ IllegalArgumentException
Occurs when passing invalid arguments to a method.
public class IllegalArgumentExample {
public static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
public static void main(String[] args) {
setAge(-5); // Throws IllegalArgumentException
}
}
✅ Prevention: Validate arguments before processing.
6️⃣ NumberFormatException
Occurs when trying to convert an invalid string into a number.
public class NumberFormatExample {
public static void main(String[] args) {
int num = Integer.parseInt("ABC"); // Throws NumberFormatException
}
}
✅ Prevention: Use exception handling or validation before parsing.
try {
int num = Integer.parseInt("ABC");
} catch (NumberFormatException e) {
System.out.println("Invalid number format!");
}
7️⃣ ClassCastException
Occurs when trying to cast an object to an incompatible type.
public class ClassCastExample {
public static void main(String[] args) {
Object obj = new String("Java");
Integer num = (Integer) obj; // Throws ClassCastException
}
}
✅ Prevention: Use instanceof
before casting.
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}
8️⃣ UnsupportedOperationException
Occurs when trying to modify an unmodifiable collection.
import java.util.*;
public class UnsupportedOperationExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C");
list.add("D"); // Throws UnsupportedOperationException
}
}
✅ Prevention: Use a modifiable collection.
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
list.add("D"); // Works fine
9️⃣ ConcurrentModificationException
Occurs when modifying a collection while iterating over it.
import java.util.*;
public class ConcurrentModificationExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String item : list) {
list.remove(item); // Throws ConcurrentModificationException
}
}
}
✅ Prevention: Use an iterator.
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
3. Summary Table of Unchecked Exceptions
Exception Type | Cause | Prevention |
---|---|---|
NullPointerException | Accessing null reference | Check for null before using objects |
ArrayIndexOutOfBoundsException | Accessing invalid array index | Validate index before access |
StringIndexOutOfBoundsException | Invalid string character index | Check string length before charAt() |
ArithmeticException | Division by zero | Ensure denominator is not zero |
IllegalArgumentException | Invalid argument passed to method | Validate input before calling methods |
NumberFormatException | Converting invalid string to number | Use try-catch for parsing numbers |
ClassCastException | Incorrect object type casting | Use instanceof before casting |
UnsupportedOperationException | Modifying an unmodifiable list | Use a modifiable collection |
ConcurrentModificationException | Modifying a collection during iteration | Use an iterator to modify safely |
Final Thoughts
✔ Unchecked exceptions occur due to bad programming logic (e.g., null access, wrong indexing).
✔ Best practice: Prevent them instead of catching them.
✔ Use built-in Java exceptions instead of creating custom unchecked exceptions.