Name several common RuntimeException types and explain what each one signals about a likely bug in the code.
answer
- NPE = used a null
- IAE = bad argument; NumberFormatException is a subclass
- ISE = wrong state / wrong time
- CCE = invalid cast
- IndexOutOfBounds = bad index; CME = mutate while iterating
basics
~10 sCommon ones: NullPointerException (used a null), IllegalArgumentException (bad argument passed in), IllegalStateException (called at the wrong time), ClassCastException (bad cast), ArrayIndexOutOfBoundsException (index past the array end), and NumberFormatException (parsed text that isn't a number).
solid answer
~40 sRuntimeExceptions flag programming mistakes. NullPointerException means you dereferenced a null reference. IllegalArgumentException means a method received an argument it explicitly forbids (e.g. a negative size). IllegalStateException means a method was invoked when the object is in an inappropriate state (e.g. iterating before initializing). ClassCastException means a cast to an incompatible type at runtime. ArrayIndexOutOfBoundsException (and the broader IndexOutOfBoundsException, plus StringIndexOutOfBoundsException) means an index was outside the valid range. NumberFormatException — a subclass of IllegalArgumentException — means string-to-number parsing failed, e.g. Integer.parseInt("abc"). ConcurrentModificationException means a collection was structurally modified while being iterated. All are unchecked: the right response is usually to fix the code that caused them rather than routinely catch them.
go deeper
Names the most common RuntimeExceptions (NPE, IAE, ArrayIndexOutOfBounds, NumberFormatException) and what triggers each.
Distinguishes IAE vs ISE, knows NumberFormatException extends IllegalArgumentException, and explains ConcurrentModificationException including the single-threaded case.
Uses these as guard-clause tools (throwing IAE/ISE deliberately), reads them as diagnoses in stack traces, and knows the correct fixes (e.g. removeIf, iterator.remove).
Establishes input-validation and fail-fast conventions across a codebase, chooses appropriate exception types for library contracts, and understands the cost/benefit of validation versus relying on natural runtime failures.
## Why these exist as a family `RuntimeException` is the unchecked sub-branch of `Exception` reserved for **programming errors** — failures that, in principle, correct code would not produce. Because they signal *bugs*, the language does not force you to declare or catch them; the proper fix is usually to correct the code, not wrap it in `try/catch`. Recognizing each type quickly tells you *what kind of mistake* occurred. ## The common members ### NullPointerException (NPE) Thrown when you try to use a `null` reference as if it pointed to an object — calling a method on it, accessing a field, indexing it, unboxing it, or throwing it. The single most common runtime exception. Since Java 14, *helpful NPE messages* name exactly which variable was null ("Cannot invoke \"String.length()\" because \"name\" is null"). ```java String s = null; int n = s.length(); // NullPointerException ``` ### IllegalArgumentException (IAE) Thrown to indicate a method was passed an argument that is unacceptable by its contract — e.g. a negative count where only non-negative is allowed. You throw this yourself in *guard clauses* to reject bad input early. ```java void setAge(int age) { if (age < 0) throw new IllegalArgumentException("age must be >= 0"); } ``` ### NumberFormatException A **subclass of `IllegalArgumentException`**, specifically for failed string→number conversions. ```java Integer.parseInt("12x"); // NumberFormatException ``` ### IllegalStateException (ISE) Thrown when a method is called at a time the object isn't ready for it — the *arguments* may be fine, but the *object's state* is wrong. E.g. calling `next()` rules, or starting an already-started thread, or modifying a builder after it was consumed. ```java Iterator<String> it = list.iterator(); it.remove(); // IllegalStateException — next() wasn't called yet ``` ### ClassCastException (CCE) Thrown when you cast an object to a type it is not actually an instance of. Common with raw collections or careless downcasts. ```java Object o = "hello"; Integer i = (Integer) o; // ClassCastException ``` ### ArrayIndexOutOfBoundsException / IndexOutOfBoundsException `IndexOutOfBoundsException` is the general case (used by `List`, etc.); `ArrayIndexOutOfBoundsException` and `StringIndexOutOfBoundsException` are array/string-specific subclasses. Thrown when an index is negative or ≥ the length. ```java int[] a = new int[3]; int x = a[3]; // ArrayIndexOutOfBoundsException (valid indices 0..2) ``` ### ConcurrentModificationException (CME) Thrown by many collections' iterators when the collection is *structurally modified* (add/remove) during iteration by anything other than the iterator's own methods. It can occur even in single-threaded code — the name refers to modification *concurrent with iteration*, not necessarily multiple threads. The fix is to use the iterator's `remove()`, collect changes and apply after, or use a copy-on-write/concurrent collection. ```java for (String s : list) { if (s.isEmpty()) list.remove(s); // ConcurrentModificationException } ``` ## How to reason about them When you see one in a stack trace, read it as a *diagnosis*: NPE → a missing null check; IAE/NumberFormat → bad input reaching a method; ISE → an operation in the wrong lifecycle order; CCE → a type assumption that was false; IndexOutOfBounds → off-by-one or unchecked bounds; CME → mutating while looping. Because all are unchecked, the goal is prevention (guards, validation, correct logic), not blanket catching.
- How do you safely remove elements from a list during iteration without a ConcurrentModificationException?Use the explicit Iterator and call iterator.remove(), or use Collection.removeIf(predicate), or iterate over a copy and modify the original, or use a concurrent/copy-on-write collection. The enhanced for-loop hides the iterator, so structural changes through the list itself trip the modCount check.
- What's the difference between IllegalArgumentException and IllegalStateException?IllegalArgumentException means the argument passed to the method is invalid regardless of object state (e.g. a negative size). IllegalStateException means the arguments may be fine but the object is in a state where the call doesn't make sense (e.g. calling start() on an already-running task). One is about the input, the other about the object's lifecycle.
saying these in an interview costs you the question
- Confusing IllegalArgumentException (bad input value) with IllegalStateException (wrong object state)
- Thinking ConcurrentModificationException only happens with multiple threads — it happens in single-threaded loops too
- Saying NumberFormatException is unrelated to IllegalArgumentException — it's a subclass
- Routinely catching these instead of fixing the underlying bug
- Believing array bounds errors are checked exceptions — they're unchecked RuntimeExceptions