Common Exceptions in Java

Naveen AnamaneniUpdated · 4 min read

A handful of exceptions cause most of the crashes you'll ever see. Each one has a typical cause, a recognizable message, and a simple way to prevent it. Learning these by sight saves hours of debugging: when you see ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3, you'll know at once to look for a loop that goes one step too far.

Seven Exceptions in One Run

Seven.java▶ Try it
import java.util.List;
 
public class Seven {
    static void attempt(String label, Runnable code) {
        try {
            code.run();
        } catch (RuntimeException e) {
            System.out.println(label + ": " + e.getClass().getSimpleName()
                + ": " + e.getMessage());
        }
    }
 
    public static void main(String[] args) {
        String name = null;
        int[] marks = {80, 90, 70};
        Object box = "Navika";
 
        attempt("null", () -> name.length());
        attempt("divide", () -> System.out.println(10 / 0));
        attempt("parse", () -> Integer.parseInt("12a"));
        attempt("cast", () -> System.out.println((Integer) box));
        attempt("index", () -> System.out.println(marks[3]));
        attempt("list", () -> List.of(1, 2).add(3));
        attempt("argument", () -> "Advitha".repeat(-1));
    }
}
Output
null: NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null
divide: ArithmeticException: / by zero
parse: NumberFormatException: For input string: "12a"
cast: ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
index: ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
list: UnsupportedOperationException: null
argument: IllegalArgumentException: count is negative: -1

How it works

attempt runs a small piece of code (written as a lambda, a short block of code passed as a value) and prints the exception it throws. Each line shows a different common exception, its exact message from Java 25, and what triggered it. The <parameter1> in the first message appears because the lambda receives name as a hidden parameter, and this example was compiled without debug names. Compiled with -g (as IDEs do), the message names the variable (see "Helpful NullPointerException Messages").

The Usual Suspects

ExceptionTypical causePrevention
NullPointerExceptionUsing a reference that is nullInitialize fields; check for null; Objects.requireNonNull early
ArithmeticExceptionInteger division by zeroCheck the divisor first
NumberFormatExceptionParsing text that isn't a numberstrip() the input; catch it for user input
ClassCastExceptionCasting an object to a type it isn'tTest with instanceof (pattern matching) first
ArrayIndexOutOfBoundsExceptionIndex below 0 or at/after lengthLoop with i < array.length
StringIndexOutOfBoundsExceptionBad position in charAt or substringCheck positions against length()
IllegalArgumentExceptionA method received a value it doesn't acceptValidate before calling; throw it yourself for bad arguments
IllegalStateExceptionCalling a method at the wrong timeCheck the object's state first
UnsupportedOperationExceptionChanging an unmodifiable collectionCopy into an ArrayList if you need changes
ConcurrentModificationExceptionChanging a list while looping over it with for-eachUse an iterator's remove, or removeIf

Common Mistakes

Wrapping everything in try instead of preventing the cause. A zero check is clearer than catching ArithmeticException.

Ignoring the message. "Index 3 out of bounds for length 3" already says the loop ran one step too far.

Confusing floating-point division with integer division. 10.0 / 0 gives Infinity, not an exception; only integer division by zero throws.

Interview Corner

Name some common runtime exceptions and their causes.

NullPointerException, from using a null reference; ArithmeticException, from integer division by zero; NumberFormatException, from parsing invalid numeric text; ClassCastException, from casting to an incompatible type; ArrayIndexOutOfBoundsException, from using an invalid array index; IllegalArgumentException and IllegalStateException, for invalid arguments or calls at the wrong time; and UnsupportedOperationException, for modifying an unmodifiable collection.

Practice

  1. Easy: For each exception in the table, write one line of code that would throw it, then fix the line so it doesn't.
  2. Harder: Write static double safeAverage(int[] marks) that never throws: it returns 0 for a null or empty array.

Quick check: Common exceptions

4 questions
1What does int x = 10 / 0; throw?
2What does Integer.parseInt("12a") throw?
3List.of(1, 2).add(3) throws:
4How do you avoid ClassCastException?

Key Takeaways

Was this tutorial helpful?

Lesson 217 of 482