Java.Core.What are the types of unchecked exceptions?

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 TypeWhen It Occurs
NullPointerExceptionAccessing methods or fields on a null object
ArrayIndexOutOfBoundsExceptionAccessing an array with an invalid index
StringIndexOutOfBoundsExceptionAccessing a string character outside its range
ArithmeticExceptionPerforming invalid arithmetic (e.g., division by zero)
IllegalArgumentExceptionPassing an invalid argument to a method
NumberFormatExceptionConverting an invalid string into a number
ClassCastExceptionIncorrect object casting
UnsupportedOperationExceptionTrying to perform an unsupported operation
ConcurrentModificationExceptionModifying 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 TypeCausePrevention
NullPointerExceptionAccessing null referenceCheck for null before using objects
ArrayIndexOutOfBoundsExceptionAccessing invalid array indexValidate index before access
StringIndexOutOfBoundsExceptionInvalid string character indexCheck string length before charAt()
ArithmeticExceptionDivision by zeroEnsure denominator is not zero
IllegalArgumentExceptionInvalid argument passed to methodValidate input before calling methods
NumberFormatExceptionConverting invalid string to numberUse try-catch for parsing numbers
ClassCastExceptionIncorrect object type castingUse instanceof before casting
UnsupportedOperationExceptionModifying an unmodifiable listUse a modifiable collection
ConcurrentModificationExceptionModifying a collection during iterationUse 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.

This entry was posted in Без рубрики. Bookmark the permalink.