Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
Exception fundamentals for the OCP 21 exam: the Throwable hierarchy, checked versus unchecked, the handle-or-declare rule, throw versus throws, unreachable catch blocks, exception rules for overriding methods and constructors, custom exceptions and printing exceptions.
kvi5hnuCode Sprout team member8 min readOn this page
An exception is how a method says "I can't finish normally, and someone else has to deal with this." Something might be wrong with the input, a file might be missing, or the code might have a bug. Instead of returning a magic value such as -1 that callers can ignore, the method throws an object describing the problem. Execution jumps out of the method, and out of each caller in turn, until some code catches it. If nobody does, the thread ends and prints a stack trace.
Return codes are still fine for expected "not found" results, such as indexOf returning -1 or Map.get returning null. Exceptions are for situations a method can't handle.
The hierarchy

Everything that can be thrown extends java.lang.Throwable. Its two main branches are:
| Type | Recognize it by | Must you handle or declare it? | Should a program catch it? |
|---|---|---|---|
| Checked exception | extends Exception but not RuntimeException | yes | yes |
| Unchecked exception (runtime exception) | extends RuntimeException | no | yes, when it makes sense |
| Error | extends Error | no (also unchecked) | no: the JVM is in trouble |
So "unchecked" means RuntimeException and its subclasses plus Error and its subclasses. Everything else is checked, including an odd class that extends Throwable directly. Memorize this table. Almost every exception question starts with "is this one checked?"
- Checked exceptions describe problems a careful program should expect, such as a missing file (
IOException) or a failed database call (SQLException). The compiler makes you deal with them. - Unchecked exceptions usually mean a bug or bad input: a
nullreference, a bad index, a bad argument. They can happen on almost any line, so requiring a declaration for each would be noise. - Errors mean the JVM itself is failing, for example by running out of memory or stack. Catching
ErrororThrowablecompiles, but application code shouldn't do it.
The handle-or-declare rule
For checked exceptions, the compiler enforces that every checked exception a method body can throw is either:
- handled, by a
try/catchthat catches that type or a supertype, or - declared, with a
throwsclause in the method signature, which hands the problem to the caller.
void load(String path) throws IOException { // declare
if (path.isBlank()) throw new IOException("no path");
}
void loadQuietly(String path) { // handle
try {
load(path);
} catch (IOException e) { // or any supertype, like Exception
System.out.println("could not load: " + e.getMessage());
}
}
void broken(String path) {
load(path); // DOES NOT COMPILE: unreported exception IOException
}
A method that only declares throws IOException without ever throwing it still forces its callers to handle or declare. The compiler trusts the signature, not the body.
Unchecked exceptions may also be caught or declared (void f() throws IllegalArgumentException compiles), but neither is required. Unchecked exceptions are usually documented in Javadoc instead.
throw versus throws
| Keyword | Where | What it does |
|---|---|---|
throw | a statement inside a method body | actually throws one exception object |
throws | the end of a method or constructor declaration | lists the exceptions the method may throw |
throw new IllegalStateException("closed"); // with a message
throw new RuntimeException(); // without one
var e = new IllegalArgumentException("bad"); // exceptions are ordinary objects...
throw e; // ...so you can create first and throw later
throw RuntimeException(); // DOES NOT COMPILE: missing new
throw null; // compiles; throws NullPointerException at runtime
The declared type of the thrown expression is what matters to the compiler. Exception e = new RuntimeException(); throw e; needs handling or a throws Exception, because the variable's type is the checked Exception.
Code that can never run is a compile error. A statement directly after a throw in the same block is unreachable:
try {
throw new RuntimeException();
throw new IllegalStateException(); // DOES NOT COMPILE: unreachable statement
} catch (Exception e) { }
Unreachable catch blocks
The compiler also rejects a catch for a checked exception that the try block can't possibly throw:
void tidy() { } // declares nothing
try {
tidy();
} catch (IOException e) { } // DOES NOT COMPILE: never thrown in body of try
This check applies only to checked exceptions other than Exception and Throwable. These all compile even when the try block throws nothing:
catch (Exception e)andcatch (Throwable e), because they also cover unchecked exceptionscatch (RuntimeException e),catch (IllegalStateException e)and other unchecked typescatch (Error e)
Overriding and exceptions
Code written against a superclass handles only what the superclass method declares. A subclass can't surprise it with new checked exceptions. When overriding (or implementing an interface method), the override:
| Override declares… | Allowed? |
|---|---|
| the same checked exceptions | yes |
| fewer checked exceptions, or none | yes |
| a subclass of a declared checked exception (narrower) | yes |
a new checked exception, or a broader one (e.g. Exception instead of IOException) | no |
| any unchecked exception | yes: unchecked exceptions are ignored by this rule |
class Courier { void deliver() throws IOException { } }
class Drone extends Courier { void deliver() throws FileNotFoundException { } } // narrower: OK
class Bike extends Courier { void deliver() { } } // none: OK
class Rocket extends Courier { void deliver() throws Exception { } } // DOES NOT COMPILE
class Glider extends Courier { void deliver() throws IllegalStateException { } } // unchecked: OK
A useful consequence: if you hold a Bike reference, bike.deliver() needs no try/catch. If you hold a Courier reference to the same object, you must handle IOException. The compiler goes by the reference type.
Constructors work the other way. Constructors aren't inherited or overridden. A subclass constructor calls the superclass constructor through super(), so it must handle or declare whatever that constructor throws. Because a checked exception from super() can't be caught there, in practice the subclass constructor must declare it or something broader:
class Base { Base() throws IOException { } }
class Derived1 extends Base { Derived1() { } } // DOES NOT COMPILE
class Derived2 extends Base { Derived2() throws Exception { } } // OK: broader is fine here
Lambdas follow the rule of the functional interface they implement. Runnable.run() declares no checked exceptions, so Runnable r = () -> { throw new IOException(); }; doesn't compile, even inside a method that declares throws IOException.
Writing your own exceptions
Extend Exception for a checked exception, or RuntimeException for an unchecked one. By convention, the name ends in Exception, though the exam may use any name. Custom exceptions usually offer the standard constructors:
public class OverdueException extends Exception {
private static final long serialVersionUID = 1L; // Throwable is Serializable
public OverdueException() { }
public OverdueException(String message) { super(message); }
public OverdueException(String message, Throwable cause) { super(message, cause); }
public OverdueException(Throwable cause) { super(cause); }
}
Constructors aren't inherited. If your exception declares only OverdueException(String), then new OverdueException() doesn't compile. The serialVersionUID line just silences a -Xlint warning.
Printing an exception
| Code | Prints |
|---|---|
System.out.println(e) | toString(): the class name, then : message if there is one, e.g. java.lang.IllegalArgumentException: perBox must be positive: 0 |
e.getMessage() | only the message, which can be null |
e.printStackTrace() | toString() plus one at … line per stack frame, written to System.err |
An uncaught exception in main prints Exception in thread "main" followed by its stack trace.
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).
- The checked and unchecked split and the
Throwablehierarchy are as old as Java. Some newer APIs, such asjava.net.httpandjava.time, favor unchecked exceptions, but the language rules are unchanged.
Exam traps from this article
A complete example
A parcel-shipping program. It defines one checked and one unchecked custom exception, handles and declares checked exceptions, and overrides a method so that it drops or narrows its checked exceptions. It prints an exception three ways, then lets the JVM throw five common runtime exceptions.
import java.io.IOException;
public class Solution {
// A checked exception: extends Exception but not RuntimeException
static class OverweightException extends Exception {
private static final long serialVersionUID = 1L; // exceptions are Serializable
OverweightException(String message) {
super(message);
}
}
// An unchecked exception: extends RuntimeException
static class LabelMissingException extends RuntimeException {
private static final long serialVersionUID = 1L;
LabelMissingException() {
super(); // no message
}
}
record Parcel(String label, double kg) {}
static String trackingCode; // never assigned, so it stays null
static class Courier {
void deliver(Parcel p) throws OverweightException, IOException {
if (p.kg() > 30) throw new OverweightException(p.kg() + " kg is over the 30 kg limit");
System.out.println(" courier delivered " + p.label());
}
}
// Overriding: may drop checked exceptions or narrow them, never add or broaden
static class Drone extends Courier {
@Override
void deliver(Parcel p) throws OverweightException { // dropped IOException
if (p.kg() > 2) throw new OverweightException("drones carry 2 kg at most");
System.out.println(" drone delivered " + p.label());
}
}
static class Bike extends Courier {
@Override
void deliver(Parcel p) { // dropped both checked exceptions
if (p.label() == null) throw new LabelMissingException(); // unchecked: no throws needed
System.out.println(" bike delivered " + p.label());
}
}
// Declare: pass the checked exceptions on to the caller
static void ship(Courier c, Parcel p) throws OverweightException, IOException {
c.deliver(p);
}
// Handle: catch the checked exceptions here
static void shipSafely(Courier c, Parcel p) {
try {
ship(c, p);
} catch (OverweightException e) {
System.out.println(" refused: " + e.getMessage());
} catch (IOException e) {
System.out.println(" network problem: " + e.getMessage());
}
}
static int boxes(int items, int perBox) {
if (perBox <= 0) throw new IllegalArgumentException("perBox must be positive: " + perBox);
return (items + perBox - 1) / perBox;
}
public static void main(String[] args) {
System.out.println("1) handle or declare");
shipSafely(new Courier(), new Parcel("books", 12));
shipSafely(new Courier(), new Parcel("piano", 240));
shipSafely(new Drone(), new Parcel("phone", 0.4));
shipSafely(new Drone(), new Parcel("kettle", 2.5));
System.out.println("2) a Bike needs no try/catch when used as a Bike");
Bike bike = new Bike();
bike.deliver(new Parcel("flowers", 1));
try {
bike.deliver(new Parcel(null, 1));
} catch (LabelMissingException e) {
System.out.println(" toString: " + e + ", message: " + e.getMessage());
}
System.out.println("3) three ways to print an exception");
try {
boxes(10, 0);
} catch (IllegalArgumentException e) {
System.out.println(" " + e);
System.out.println(" " + e.getMessage());
StackTraceElement top = e.getStackTrace()[0];
System.out.println(" thrown in " + top.getMethodName() + "(), stack depth " + e.getStackTrace().length);
}
System.out.println("4) exceptions the JVM throws for you");
int[] shelf = new int[2];
Object weight = Double.valueOf(4.5);
Runnable[] mistakes = {
() -> System.out.println(shelf[2]),
() -> System.out.println(7 / (shelf.length - 2)),
() -> System.out.println((String) weight),
() -> System.out.println(trackingCode.length()),
() -> System.out.println(Integer.parseInt("12kg")),
};
for (Runnable r : mistakes) {
try {
r.run();
} catch (RuntimeException e) {
String msg = e.getMessage();
int cut = msg.indexOf(" ("); // trim the long module details
System.out.println(" " + e.getClass().getSimpleName() + ": "
+ (cut > 0 ? msg.substring(0, cut) : msg));
}
}
System.out.println("boxes(10, 4) = " + boxes(10, 4));
}
}
Output:
1) handle or declare
courier delivered books
refused: 240.0 kg is over the 30 kg limit
drone delivered phone
refused: drones carry 2 kg at most
2) a Bike needs no try/catch when used as a Bike
bike delivered flowers
toString: Solution$LabelMissingException, message: null
3) three ways to print an exception
java.lang.IllegalArgumentException: perBox must be positive: 0
perBox must be positive: 0
thrown in boxes(), stack depth 2
4) exceptions the JVM throws for you
ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
ArithmeticException: / by zero
ClassCastException: class java.lang.Double cannot be cast to class java.lang.String
NullPointerException: Cannot invoke "String.length()" because "Solution.trackingCode" is null
NumberFormatException: For input string: "12kg"
boxes(10, 4) = 3
Points to notice:
shipSafelyhandles both checked exceptions, whileshipsimply declares them and passes them on.Drone.deliverdroppedIOException, andBike.deliverdropped both, so code holding aBikereference calleddeliverwithout atry.LabelMissingExceptionwas thrown without a message:toString()printed just the class name, andgetMessage()returnednull.- The JVM threw every exception in part 4 by itself. They're all
RuntimeExceptions, so onecatch (RuntimeException e)caught them all. TheNullPointerExceptionmessage named thenullfield.
Common questions
Should I use checked or unchecked exceptions for my own code? Use checked when the caller can reasonably recover (retry, ask for another file). Use unchecked for programming errors and invalid arguments. Modern APIs, and lambdas, lean toward unchecked.
Why doesn't catch (Exception e) cause an "unreachable catch" error?
Because Exception includes RuntimeException, which any code can throw. The compiler can never prove the block is unreachable.
Is throws part of the method signature for overloading?
No. The signature is the name plus the parameter types. Two methods that differ only in their throws clause are a duplicate-method compile error.
Summary
Throwablesplits intoErrorandException.RuntimeException(underException) andErrorare unchecked, and everything else is checked.- Checked exceptions must be handled with
try/catchor declared withthrows. throwthrows an object;throwsdeclares. Unreachable statements and impossible checkedcatchblocks don't compile.- Overrides can't add or broaden checked exceptions. Constructors must declare those of
super()or broader ones. - Custom exceptions extend
ExceptionorRuntimeExceptionand declare their own constructors. - Print with
toString(),getMessage()orprintStackTrace(). Java 21 gives helpfulNullPointerExceptionmessages.
Practice quiz
Test yourself with the checked and unchecked exceptions quiz: 10 exam-style questions with explanations.
Previous: Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (OCP 21)
Next: Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
Related reading
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
- Java Logging Basics: System.Logger and java.util.logging
- Java Assertions: Using assert, Enabling Assertions and Design by Contract

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.