Java Exceptions: The Exception Hierarchy, Checked and Unchecked
Start Java exception handling the right way: why exceptions beat error codes, the Throwable hierarchy with Error, Exception and RuntimeException, checked vs unchecked exceptions, declaring exceptions with throws, and the rules for overriding methods that throw.
kvi5hnuCode Sprout team member14 min readOn this page
In a perfect world, users would never enter data in the wrong format, files they open would always exist, and code would never have bugs. So far, most code in this course has been written as if we lived in that world. It's time to look at Java's mechanisms for dealing with the real world of bad data and buggy code.
Encountering errors is unpleasant. If users lose all their work because of a programming mistake or some external circumstance, they may never come back to your program. At the very least, you must
- notify the user of an error,
- save all work, and
- allow users to exit the program gracefully.
For exceptional situations, such as bad input data that could crash the program, Java uses a form of error trapping called exception handling. It's similar to exception handling in C++, C# or Python. This part of the course covers three topics:
- Exceptions: how to signal, declare, catch and design them (this and the next four articles).
- Assertions: checks you can switch on during testing and off in production.
- Logging: recording problems for later analysis, when you can't simply tell the user or terminate.
Dealing with Errors
Suppose an error occurs while a Java program runs. It might be caused by a file with wrong information, a flaky network connection, or (sadly) an invalid array index or an object reference that hasn't been assigned yet. Users expect programs to act sensibly when errors happen. If an operation can't be completed because of an error, the program should either
- return to a safe state and let the user execute other commands, or
- allow the user to save all work and terminate gracefully.
That may not be easy, because the code that detects the error is usually far away from the code that can roll back the data or save the user's work. The mission of exception handling is to transfer control from where the error occurred to an error handler that can deal with the situation.
What sorts of problems do you need to consider?
- User input errors. Besides the inevitable typos, some users like to blaze their own trail instead of following directions. Suppose a user asks to connect to a syntactically wrong URL. Your code should check the syntax, but if it doesn't, the network layer will complain.
- Device errors. Hardware doesn't always do what you want. A printer may be off; a web service may be temporarily unavailable. Devices often fail in the middle of a task, like a printer running out of paper.
- Physical limitations. Disks fill up, and you can run out of memory.
- Code errors. A method may not work correctly: it may deliver wrong answers or use other methods incorrectly. Computing an invalid array index, looking up a nonexistent entry in a hash table, and popping an empty stack are all code errors.
Error codes versus exceptions
The traditional reaction to an error is to return a special error code that the caller analyzes. Methods that read from files often return -1 at the end of the file instead of a regular character. Another common error value is the null reference.
But it isn't always possible to return an error code. There may be no obvious way to distinguish valid from invalid data. A method returning an integer can't simply return -1 for an error, because -1 might be a perfectly valid result.
Returning null is particularly problematic. The listFiles method of the legacy java.io.File class returns a File[] array, or null on failure. If the programmer forgets to check, a NullPointerException occurs when the result is first used, masking the original problem. You can see this in the demo below: listFiles on a missing directory just returns null.
Java gives every method an alternative exit path for when it can't complete its task normally. Then the method doesn't return a value. Instead, it throws an object that encapsulates the error information. The method exits immediately, without returning its normal (or any) value. And execution doesn't resume at the calling code; instead, the exception-handling mechanism searches for an exception handler that can deal with this particular error condition.
Exceptions have their own syntax and a special inheritance hierarchy. Let's look at the hierarchy first.
The Classification of Exceptions
In Java, an exception object is always an instance of a class derived from Throwable. You can also create your own exception classes, as the next article shows.

All exceptions descend from Throwable, but the hierarchy immediately splits into two branches: Error and Exception.
Error
The Error hierarchy describes internal errors and resource exhaustion inside the Java runtime: OutOfMemoryError, StackOverflowError, NoClassDefFoundError, and so on. You shouldn't throw objects of this type. There's little you can do when such an error occurs, beyond notifying the user and trying to terminate gracefully. These situations are quite rare.
Exception and RuntimeException
When programming in Java, focus on the Exception hierarchy. It also splits into two branches: exceptions derived from RuntimeException and those that aren't. The general rule:
A
RuntimeExceptionhappens because you made a programming error. Any other exception happens because something bad, such as an I/O error, happened to your otherwise good program.
Exceptions that inherit from RuntimeException include problems such as
- a bad cast (
ClassCastException), - an out-of-bounds array access (
ArrayIndexOutOfBoundsException), - a null pointer access (
NullPointerException), - an illegal argument (
IllegalArgumentException, and its subclassNumberFormatException).
Exceptions that don't inherit from RuntimeException include
- trying to read past the end of a file (
EOFException), - trying to open a file that doesn't exist (
FileNotFoundException), - trying to find a
Classobject for a string that doesn't denote an existing class (ClassNotFoundException).
The rule "if it's a RuntimeException, it was your fault" works pretty well. You could have avoided that ArrayIndexOutOfBoundsException by testing the index against the array bounds. The NullPointerException wouldn't have happened if you had checked whether the variable was null.
What about a file that doesn't exist? Can't you first check whether it exists, and then open it? Well, the file might be deleted right after you checked. So "existence" depends on the environment, not just on your code. That's what makes it a checked exception.
Checked and unchecked exceptions
The Java Language Specification calls any exception that derives from Error or RuntimeException an unchecked exception. All other exceptions are checked exceptions. The compiler checks that you provide exception handlers, or declarations, for all checked exceptions.
| Unchecked | Checked | |
|---|---|---|
| Classes | Error, RuntimeException and their subclasses | All other subclasses of Exception (and Throwable) |
| Typical cause | Programming errors, JVM problems | Conditions outside your control: I/O, network, missing classes |
| Compiler requirement | None | Must be caught or declared with throws |
| Examples | NullPointerException, IllegalStateException, OutOfMemoryError | IOException, SQLException, InterruptedException |
Here's how common exceptions are classified, printed by a program that walks up each class's superclass chain:
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// where do common exceptions sit in the hierarchy?
Throwable[] samples = {
new ArrayIndexOutOfBoundsException(), new NullPointerException(),
new ClassCastException(), new IllegalArgumentException(), new NumberFormatException(),
new FileNotFoundException(), new EOFException(), new ClassNotFoundException(),
new OutOfMemoryError(), new StackOverflowError() };
for (Throwable t : samples)
System.out.printf("%-30s %-10s %s%n", t.getClass().getSimpleName(), kind(t), chain(t.getClass()));
// unchecked: a programming error you could have avoided
int[] a = new int[3];
try {
a[3] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("caught: " + e.getMessage());
}
// checked: something outside your control; the compiler insists you deal with it
try {
System.out.println(firstLine("no-such-file.txt"));
} catch (IOException e) {
System.out.println("caught: " + e.getClass().getSimpleName());
}
// an error code that is easy to overlook, versus an exception that isn't
File legacy = new File("no-such-dir");
System.out.println("File.listFiles returned " + Arrays.toString(legacy.listFiles()));
System.out.println("File.delete returned " + legacy.delete());
try {
Files.delete(Path.of("no-such-dir"));
} catch (IOException e) {
System.out.println("Files.delete threw " + e.getClass().getSimpleName());
}
}
/** Declares the checked exception instead of handling it. */
static String firstLine(String fileName) throws IOException {
try (var in = new BufferedReader(new FileReader(fileName))) {
return in.readLine();
}
}
static String kind(Throwable t) {
if (t instanceof Error) return "unchecked";
if (t instanceof RuntimeException) return "unchecked";
return "checked";
}
static String chain(Class<?> cl) {
var names = new ArrayList<String>();
for (Class<?> c = cl.getSuperclass(); c != Object.class; c = c.getSuperclass())
names.add(c.getSimpleName());
return String.join(" < ", names);
}
}
class Animation {
public String loadImage(String s) throws IOException { return s; }
public void draw() { }
}
class FastAnimation extends Animation {
@Override
public String loadImage(String s) throws FileNotFoundException { return s; } // more specific: OK
@Override
public void draw() { /* may not throw checked exceptions: the superclass method doesn't */ }
}
ArrayIndexOutOfBoundsException unchecked IndexOutOfBoundsException < RuntimeException < Exception < Throwable
NullPointerException unchecked RuntimeException < Exception < Throwable
ClassCastException unchecked RuntimeException < Exception < Throwable
IllegalArgumentException unchecked RuntimeException < Exception < Throwable
NumberFormatException unchecked IllegalArgumentException < RuntimeException < Exception < Throwable
FileNotFoundException checked IOException < Exception < Throwable
EOFException checked IOException < Exception < Throwable
ClassNotFoundException checked ReflectiveOperationException < Exception < Throwable
OutOfMemoryError unchecked VirtualMachineError < Error < Throwable
StackOverflowError unchecked VirtualMachineError < Error < Throwable
caught: Index 3 out of bounds for length 3
caught: FileNotFoundException
File.listFiles returned null
File.delete returned false
Files.delete threw NoSuchFileException
Declaring Checked Exceptions
A Java method can throw an exception when it encounters a situation it can't handle. The idea is simple: a method tells the compiler not only what values it can return, but also what can go wrong. Code that reads from a file knows the file might not exist or might be empty, so it notifies the compiler that it can throw some sort of IOException.
You advertise that a method can throw an exception in its header, with a throws clause. Here's one of the constructors of FileInputStream from the standard library:
public FileInputStream(String name) throws FileNotFoundException
It says the constructor produces a FileInputStream from a String, but it can also go wrong in a special way: by throwing a FileNotFoundException. If that happens, the constructor doesn't initialize a new object. It throws a FileNotFoundException, and the runtime system searches for an exception handler that knows how to deal with it.
What must be declared?
You don't have to advertise every possible throwable object. An exception is thrown in one of four situations:
- You call a method that throws a checked exception, such as the
FileInputStreamconstructor. - You detect an error and throw a checked exception with the
throwstatement (next article). - You make a programming error, such as
a[-1] = 0, which gives rise to an unchecked exception (here anArrayIndexOutOfBoundsException). - An internal error occurs in the virtual machine or runtime library.
In the first two cases, you must tell programmers who use your method about the possibility of an exception. Why? Any method that throws an exception is a potential death trap: if no handler catches it, the current thread terminates.
Declare the exception with an exception specification in the method header:
class MyAnimation {
. . .
public Image loadImage(String s) throws IOException {
. . .
}
}
If a method might throw several checked exception types, list them all, separated by commas:
public Image loadImage(String s) throws FileNotFoundException, EOFException
You don't need to advertise internal Java errors, the exceptions inheriting from Error. Any code could potentially throw them, and they're entirely beyond your control.
Similarly, you shouldn't advertise unchecked exceptions inheriting from RuntimeException:
void drawImage(int i) throws ArrayIndexOutOfBoundsException // bad style
These runtime errors are completely under your control. If you're worried about array index errors, spend your time fixing them instead of advertising that they can happen. (Documenting them in javadoc with @throws, for example @throws IllegalArgumentException if width is negative, is a different matter, and encouraged.)
In summary, a method must declare all the checked exceptions it might throw. Unchecked exceptions are either beyond your control (Error) or result from conditions you shouldn't have allowed in the first place (RuntimeException). If a method fails to declare a checked exception, the compiler reports an error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown.
Instead of declaring an exception, you can also catch it. Then it won't escape the method, and no throws clause is needed. You'll see how to decide between catching and declaring in the try/catch article.
Declaring a superclass
When a method declares that it throws an exception of some class, it may throw an exception of that class or any of its subclasses. The FileInputStream constructor could have declared throws IOException. Then you wouldn't know what kind of IOException it is: a plain IOException, or one of its subclasses such as FileNotFoundException. Declaring the most specific type gives callers more information.
Overriding and exceptions
The reason is substitutability: code that calls animation.loadImage(...) through a superclass reference has prepared only for the exceptions the superclass declares. In the demo, FastAnimation.loadImage legally narrows IOException to FileNotFoundException.
Common questions
Should I catch Errors like OutOfMemoryError?
Generally no. The JVM may be in a state where recovery isn't possible. Top-level code (a server's request loop or a thread's uncaught-exception handler) may catch Throwable to log the problem and shut down cleanly. Ordinary code should let errors propagate.
Is NullPointerException checked?
No, it's a RuntimeException, so it's unchecked. Prevent it by validating inputs (Objects.requireNonNull), avoiding null returns (use empty collections or Optional), and reading the helpful NPE messages that name the null expression.
Why is IOException checked but NumberFormatException unchecked?
An I/O failure depends on the environment: the file may vanish between your check and your read, so callers should plan for it. A NumberFormatException usually means that code passed unchecked text to parseInt, which validation could have prevented. In practice, parsing user input is a borderline case, which is why many developers catch NumberFormatException anyway.
Can I declare throws Exception on everything to avoid compiler errors?
You can, but it destroys the information that checked exceptions give callers, and forces them to catch everything. Declare the specific checked exceptions, or wrap them in a meaningful exception for your layer.
Do checked exceptions exist in the JVM?
No. Checked exceptions are purely a compile-time feature of the Java language. The JVM lets any method throw any Throwable. That's why other JVM languages such as Kotlin can ignore them, and why tricks like "sneaky throws" exist. Don't use those tricks in normal code.
Summary
- Exceptions transfer control from the point where an error is detected to a handler that can deal with it, and they can't be silently ignored the way error codes or
nullcan. - All exceptions derive from
Throwable.Errorcovers JVM-level problems;Exceptioncovers everything you deal with as a programmer. RuntimeExceptionsignals programming errors (bad casts, bad indexes,nullaccess). Other exceptions signal problems outside your control (I/O, missing classes).- Unchecked =
ErrorandRuntimeExceptionsubclasses. Checked = all others; the compiler requires you to catch or declare them. - Declare checked exceptions with
throwsin the method header. Don't declareErrors orRuntimeExceptions (but do document them). - Overriding methods may declare fewer or more specific checked exceptions, never more general ones.
Practice Questions
Classify as checked or unchecked: NumberFormatException, FileNotFoundException, StackOverflowError, InterruptedException, IllegalStateException.
Unchecked: NumberFormatException (a RuntimeException), StackOverflowError (an Error) and IllegalStateException. Checked: FileNotFoundException (an IOException) and InterruptedException.
Why is "file not found" a checked exception, when you could check whether the file exists first?
The file system can change between your check and your use: another process can delete the file. The condition depends on the environment, not on your code, so the caller must be prepared for it.
A method calls new FileReader(name) and neither catches nor declares anything. What does the compiler say, and what are your two options?
unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown. Either add throws FileNotFoundException (or IOException) to the method header, or wrap the call in a try/catch block.
Superclass: void save() throws IOException. Which overrides compile: (a) void save() (b) void save() throws FileNotFoundException (c) void save() throws Exception (d) void save() throws IllegalStateException
(a), (b) and (d) compile. (c) doesn't, because Exception is more general than IOException. (d) is fine because unchecked exceptions are never restricted.
Why is returning null on failure, as File.listFiles does, considered bad design?
Callers can forget to check, and the error then surfaces later as a NullPointerException far from the cause, without any information about what went wrong. An exception reports the problem immediately and explains it.
Previous: Java Dynamic Proxies: Implementing Interfaces at Runtime
Next: Throwing Exceptions and Creating Custom Exception Classes in Java
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.