Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
The exception classes the OCP 21 exam expects you to recognize: ArithmeticException, ArrayIndexOutOfBounds, ClassCastException, NullPointerException, IllegalArgument and NumberFormat, IOException and FileNotFound, ParseException, and Errors like StackOverflowError and ExceptionInInitializerError.
kvi5hnuCode Sprout team member7 min readOn this page
Exam questions rarely say "this is an exception question." A question that looks like it's about arrays, casting or parsing often has "throws an exception at runtime" as its correct answer. For each class here, you need to know three things:
- Is it checked or unchecked?
- Who usually throws it: the JVM or code (the JDK libraries or a programmer)?
- Which subclass relationships matter? These decide whether
catchblocks are reachable, as the next article shows.

Unchecked: RuntimeException and its subclasses
Thrown by the JVM
| Exception | Cause | Example |
|---|---|---|
ArithmeticException | integer division (or %) by zero | int r = 10 / 0; gives the message / by zero |
ArrayIndexOutOfBoundsException | array index < 0 or >= length | int[] a = new int[3]; a[-1] = 0; gives Index -1 out of bounds for length 3 (a negative size in new int[-1] is a NegativeArraySizeException instead) |
ClassCastException | a cast the compiler allowed fails at runtime | Object o = "seven"; Integer i = (Integer) o; |
NullPointerException | using a null reference as an object | calling a method, reading a field, unboxing null, throw null |
ArrayStoreException | storing the wrong type into an array through a supertype reference | Object[] a = new String[1]; a[0] = 4; |
NegativeArraySizeException | creating an array with a negative length | new int[-2] |
Floating-point division by zero does not throw: 10.0 / 0 is Infinity, and 0.0 / 0 is NaN.
A cast between types the compiler knows are unrelated doesn't even compile. Integer n = (Integer) "moose"; fails with incompatible types. A ClassCastException needs a reference type that could hold the target, such as Object.
Thrown by code (libraries or programmers)
| Exception | Usual meaning | Typical source |
|---|---|---|
IllegalArgumentException | a method got an argument it can't accept | your own guard clauses: if (n < 0) throw new IllegalArgumentException(...) |
NumberFormatException (subclass of IllegalArgumentException) | a String isn't a valid number | Integer.parseInt("12.5"), Integer.valueOf("abc") |
IllegalStateException | the object isn't in the right state for this call | Iterator.remove() before next(), using a consumed stream, a full ArrayBlockingQueue.add |
UnsupportedOperationException | the operation isn't supported | List.of("x").add("y"), Arrays.asList(...).remove(0) |
NoSuchElementException | there's no element to return | iterator.next() at the end, Optional.empty().get(), orElseThrow() |
ConcurrentModificationException | a collection changed while being iterated | removing from a list inside a for-each loop |
IndexOutOfBoundsException | a bad index for a list or string (parent of the array and string versions) | List.of(1).get(3); "abc".charAt(5) gives StringIndexOutOfBoundsException |
DateTimeException | an invalid date or time | LocalDate.of(2025, 13, 1); parsing gives the subclass DateTimeParseException |
MissingResourceException | a resource bundle or key can't be found | ResourceBundle.getBundle("Nope") (see article 72) |
UncheckedIOException | wraps an IOException where checked exceptions aren't allowed | Files.lines(...) stream operations |
NumberFormatException being a subclass of IllegalArgumentException is the relationship the exam tests most often.
Checked: Exception but not RuntimeException
| Exception | Package | Thrown when | Relationship |
|---|---|---|---|
IOException | java.io | reading or writing fails | parent of the next three |
FileNotFoundException | java.io | opening a missing file with FileReader or FileInputStream | subclass of IOException |
NotSerializableException | java.io | serializing an object that isn't Serializable | subclass of IOException (via ObjectStreamException) |
ParseException | java.text | NumberFormat.parse or DateFormat.parse fails | direct subclass of Exception |
SQLException | java.sql | database access fails | direct subclass of Exception |
InterruptedException | java.lang | a waiting thread is interrupted (Thread.sleep, join) | direct subclass of Exception |
Two parsing traps:
NumberFormat.parsethrows the checkedParseException, whileInteger.parseIntthrows the uncheckedNumberFormatException.java.timeparsing (LocalDate.parse) throws the uncheckedDateTimeParseException.
The NIO.2 file methods in Files throw IOException subclasses such as NoSuchFileException. Chapter 14 covers them.
Errors: subclasses of Error
Errors are unchecked. The JVM throws them, and your code generally shouldn't catch them.
| Error | Thrown when |
|---|---|
StackOverflowError | the call stack runs out, almost always from infinite recursion |
OutOfMemoryError | the heap can't satisfy an allocation |
ExceptionInInitializerError | a static initializer or static field initializer throws an exception. The original exception becomes its cause. |
NoClassDefFoundError | a class was present at compile time but can't be loaded at runtime, including a class whose static initialization already failed once |
AssertionError | an assert statement fails (with -ea), or code throws one explicitly |
The complete example shows the static-initializer pair. The first use of the broken class throws ExceptionInInitializerError, and every later use throws NoClassDefFoundError.
Don't confuse these two. ClassNotFoundException is a checked exception, thrown by reflective loading such as Class.forName("Nope"). NoClassDefFoundError is an Error.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- With the Security Manager permanently disabled in Java 24 (JEP 486),
SecurityExceptionis rarely thrown by the JDK any more. It still exists, and the exam can still name it.
Exam traps from this article
A complete example
The program provokes each exception from this article on purpose. A small probe helper catches whatever was thrown and prints whether it's checked, along with its superclass chain up to Exception or Error. That's the relationship information the exam relies on.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
public class Solution {
// A class whose static initializer fails
static class Config {
static final int PORT = Integer.parseInt("80a"); // NumberFormatException during class init
}
interface Risky {
void run() throws Exception;
}
// Runs code that should fail and describes what was thrown
static void probe(String label, Risky code) {
try {
code.run();
System.out.println(label + ": no exception");
} catch (Exception | Error t) {
String kind = t instanceof RuntimeException || t instanceof Error ? "unchecked" : "CHECKED";
System.out.printf("%-16s %-9s %s%n", label + ":", kind, chain(t.getClass()));
}
}
// ArithmeticException -> RuntimeException, stopping before Exception/Error/Throwable
static String chain(Class<?> c) {
StringBuilder sb = new StringBuilder(c.getSimpleName());
for (Class<?> p = c.getSuperclass(); p != Exception.class && p != Error.class
&& p != Throwable.class; p = p.getSuperclass()) {
sb.append(" -> ").append(p.getSimpleName());
}
return sb.toString();
}
static int depth(int n) {
return depth(n + 1) + 1; // no base case: infinite recursion
}
public static void main(String[] args) {
int[] seats = new int[3];
Object boxed = "seven";
String nothing = args.length > 99 ? "x" : null;
List<String> queue = new ArrayList<>(List.of("a", "b", "c"));
System.out.println("--- thrown by the JVM ---");
probe("divide", () -> System.out.println(10 / seats[0]));
probe("array index", () -> System.out.println(seats[3]));
probe("string index", () -> System.out.println("abc".charAt(5)));
probe("cast", () -> System.out.println((Integer) boxed));
probe("null", () -> System.out.println(nothing.length()));
probe("array store", () -> { Object[] o = new String[1]; o[0] = 4; });
probe("negative size", () -> System.out.println(new int[seats.length - 4].length));
System.out.println("--- thrown by library or programmer code ---");
probe("parseInt", () -> Integer.parseInt("12.5"));
probe("bad argument", () -> LocalDate.of(2025, 13, 1));
probe("immutable", () -> List.of("x").add("y"));
probe("empty iterator", () -> List.of().iterator().next());
probe("modified", () -> { for (String s : queue) queue.remove(s); });
probe("state", () -> {
Iterator<String> it = queue.iterator();
it.remove(); // remove() before next()
});
System.out.println("--- checked exceptions ---");
probe("missing file", () -> new FileReader("no-such-file.txt").close());
probe("parse", () -> NumberFormat.getInstance(Locale.US).parse("abc"));
probe("io", () -> { throw new IOException("disk full"); });
System.out.println("--- errors ---");
probe("recursion", () -> depth(0));
probe("static init", () -> System.out.println(Config.PORT));
probe("init again", () -> System.out.println(Config.PORT));
// Subclass relationships the exam relies on
System.out.println("--- is-a checks ---");
System.out.println("NumberFormatException is an IllegalArgumentException: "
+ (new NumberFormatException() instanceof IllegalArgumentException));
System.out.println("FileNotFoundException is an IOException: "
+ (new FileNotFoundException() instanceof IOException));
System.out.println("ParseException is a RuntimeException: "
+ RuntimeException.class.isAssignableFrom(ParseException.class));
}
}
Output:
--- thrown by the JVM ---
divide: unchecked ArithmeticException -> RuntimeException
array index: unchecked ArrayIndexOutOfBoundsException -> IndexOutOfBoundsException -> RuntimeException
string index: unchecked StringIndexOutOfBoundsException -> IndexOutOfBoundsException -> RuntimeException
cast: unchecked ClassCastException -> RuntimeException
null: unchecked NullPointerException -> RuntimeException
array store: unchecked ArrayStoreException -> RuntimeException
negative size: unchecked NegativeArraySizeException -> RuntimeException
--- thrown by library or programmer code ---
parseInt: unchecked NumberFormatException -> IllegalArgumentException -> RuntimeException
bad argument: unchecked DateTimeException -> RuntimeException
immutable: unchecked UnsupportedOperationException -> RuntimeException
empty iterator: unchecked NoSuchElementException -> RuntimeException
modified: unchecked ConcurrentModificationException -> RuntimeException
state: unchecked IllegalStateException -> RuntimeException
--- checked exceptions ---
missing file: CHECKED FileNotFoundException -> IOException
parse: CHECKED ParseException
io: CHECKED IOException
--- errors ---
recursion: unchecked StackOverflowError -> VirtualMachineError
static init: unchecked ExceptionInInitializerError -> LinkageError
init again: unchecked NoClassDefFoundError -> LinkageError
--- is-a checks ---
NumberFormatException is an IllegalArgumentException: true
FileNotFoundException is an IOException: true
ParseException is a RuntimeException: false
Points to notice:
- Every JVM-thrown problem was unchecked. The index exceptions share the parent
IndexOutOfBoundsException. Integer.parseInt("12.5")threwNumberFormatException, whose chain showsIllegalArgumentExceptionas its parent.LocalDate.of(2025, 13, 1)threw the uncheckedDateTimeException, whileNumberFormat.parse("abc")threw the checkedParseException.- Opening a missing file threw the checked
FileNotFoundException, a subclass ofIOException. - The
Configclass failed during static initialization. The first access gaveExceptionInInitializerError, and the second gaveNoClassDefFoundError. - The
probehelper caughtErrors only to describe them. Real programs should let them propagate.
Common questions
Do I need to memorize exception messages?
No. The exam shows output like Exception in thread "main" java.lang.ArithmeticException: / by zero, but you're tested on which exception is thrown, not on its exact wording.
When should my code throw IllegalArgumentException versus IllegalStateException?
Throw IllegalArgumentException when the caller's input is wrong, and IllegalStateException when the object isn't ready, for example "already closed" or "not started".
Is Exception itself checked?
Yes. throw new Exception() must be handled or declared, even though catch (Exception e) also catches runtime exceptions.
Summary
- Unchecked, from the JVM:
ArithmeticException,ArrayIndexOutOfBoundsException,ClassCastException,NullPointerException,ArrayStoreException,NegativeArraySizeException. - Unchecked, from code:
IllegalArgumentException(and its subclassNumberFormatException),IllegalStateException,UnsupportedOperationException,NoSuchElementException,ConcurrentModificationException,DateTimeException,MissingResourceException. - Checked:
IOException(withFileNotFoundExceptionandNotSerializableException),ParseException,SQLException,InterruptedException. - Errors:
StackOverflowError,OutOfMemoryError,ExceptionInInitializerError,NoClassDefFoundError,AssertionError.
Practice quiz
Test yourself with the common exception classes quiz: 10 exam-style questions with explanations.
Previous: Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
Next: Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
Related reading
- Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
- Java Generics: Generic Classes, Interfaces, Methods and Type Erasure (OCP 21)
- Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)
- Java Local and Anonymous Classes (OCP 21)
- Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.