Un-checked Exceptions

Unchecked exceptions in Java, also known as runtime exceptions, do not require you to declare them using the throws clause or handle them explicitly using a try-catch block. They usually occur at runtime and are not checked by the compiler. Below are some common unchecked exceptions along with examples:

  1. NullPointerException: Occurs when you try to access a method or field on a null object.

    public class NullPointerExceptionExample {
        public static void main(String[] args) {
            String str = null;
            int length = str.length(); // This will throw a NullPointerException
        }
    }
  2. ArrayIndexOutOfBoundsException: Happens when you try to access an array element with an invalid index.

    public class ArrayIndexOutOfBoundsExceptionExample {
        public static void main(String[] args) {
            int[] arr = {1, 2, 3};
            int value = arr[5]; // This will throw an ArrayIndexOutOfBoundsException
        }
    }
  3. ArithmeticException: Occurs when you perform an arithmetic operation that's not valid, such as dividing by zero.

    public class ArithmeticExceptionExample {
        public static void main(String[] args) {
            int result = 5 / 0; // This will throw an ArithmeticException
        }
    }
  4. NumberFormatException: Raised when you try to parse a string to a number, but the string doesn't represent a valid number.

    public class NumberFormatExceptionExample {
        public static void main(String[] args) {
            int num = Integer.parseInt("abc"); // This will throw a NumberFormatException
        }
    }
  5. IllegalArgumentException: Occurs when an illegal argument is passed to a method.

    public class IllegalArgumentExceptionExample {
        public static void main(String[] args) {
            int age = -5;
            if (age < 0) {
                throw new IllegalArgumentException("Age cannot be negative.");
            }
        }
    }
  6. ClassCastException: Raised when you try to cast an object to an incompatible class.

    public class ClassCastExceptionExample {
        public static void main(String[] args) {
            Object obj = "Hello";
            Integer num = (Integer) obj; // This will throw a ClassCastException
        }
    }

It's important to note that while unchecked exceptions do not require explicit handling, it's still a good practice to handle them when you can anticipate them to avoid unexpected program crashes and improve the robustness of your code.

Last updated