Common Exceptions in Java
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
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));
}
}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: -1How 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
| Exception | Typical cause | Prevention |
|---|---|---|
NullPointerException | Using a reference that is null | Initialize fields; check for null; Objects.requireNonNull early |
ArithmeticException | Integer division by zero | Check the divisor first |
NumberFormatException | Parsing text that isn't a number | strip() the input; catch it for user input |
ClassCastException | Casting an object to a type it isn't | Test with instanceof (pattern matching) first |
ArrayIndexOutOfBoundsException | Index below 0 or at/after length | Loop with i < array.length |
StringIndexOutOfBoundsException | Bad position in charAt or substring | Check positions against length() |
IllegalArgumentException | A method received a value it doesn't accept | Validate before calling; throw it yourself for bad arguments |
IllegalStateException | Calling a method at the wrong time | Check the object's state first |
UnsupportedOperationException | Changing an unmodifiable collection | Copy into an ArrayList if you need changes |
ConcurrentModificationException | Changing a list while looping over it with for-each | Use 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
- Easy: For each exception in the table, write one line of code that would throw it, then fix the line so it doesn't.
- Harder: Write
static double safeAverage(int[] marks)that never throws: it returns 0 for a null or empty array.
Key Takeaways
Was this tutorial helpful?