Java Exception Handling Best Practices: Tips Every Developer Should Know
Practical Java exception handling best practices: don't use exceptions for control flow, keep try blocks coarse, use precise types, never swallow exceptions, throw early and catch late, validate with Objects methods, and keep stack traces away from users.
kvi5hnuCode Sprout team member11 min readOn this page
You now know the mechanics of exceptions: throwing, catching, chaining, finally and try-with-resources. Using them well is a different skill, and a contested one. Some developers regard every checked exception as a nuisance; others throw them at every opportunity. Exceptions, checked ones included, have their place. The guidelines below, collected from the JDK's own design, long experience and code reviews, help you put them in the right place.

1. Exceptions are not a replacement for a simple test
Throwing and catching is much more expensive than an if. The JVM has to create the exception object, capture the stack trace (the costly part), and unwind frames until a handler is found. Compare two ways to empty a stack:
if (!s.isEmpty()) s.pop();
versus forcing the pop and catching the failure:
try {
s.pop();
} catch (EmptyStackException e) {
}
Run each millions of times and the exception-based version is slower by an order of magnitude or more. Speed isn't even the main issue. The try version hides the program's logic: a reader sees a catch and assumes something went wrong, when emptiness is a perfectly normal state.
Use exceptions for exceptional circumstances only. If a situation is expected, test for it, or use an API that reports it without an exception: Deque.poll returns null for an empty deque, Map.getOrDefault supplies a default, Optional models a missing value, and Integer.parseInt is best preceded by validation when bad input is common.
2. Don't micromanage exceptions
Some programmers wrap every single statement in its own try block:
for (i = 0; i < 100; i++) {
try {
n = s.pop();
} catch (EmptyStackException e) {
// stack was empty
}
try {
out.writeInt(n);
} catch (IOException e) {
// problem writing to file
}
}
The code balloons and becomes hard to follow. Think about the task as a whole: pop 100 numbers and save them to a file. If the stack is empty, it won't fill up again. If writing fails, the next write will fail too. Nothing useful can be done per statement, so wrap the entire task and abandon it if any step fails:
try {
for (i = 0; i < 100; i++) {
n = s.pop();
out.writeInt(n);
}
} catch (IOException e) {
// problem writing to file
} catch (EmptyStackException e) {
// stack was empty
}
This delivers one of the main promises of exception handling: normal processing is separated from error handling.
3. Make good use of the exception hierarchy
- Throw precise types. Don't throw a plain
ExceptionorRuntimeException. Find a fitting subclass, or create your own. - Catch precise types. Don't just catch
Exception. It makes code hard to read and maintain, and it catches things you didn't plan for, including everyRuntimeException, which often indicates a bug. Catch only the classes you expect. - Never catch
ThrowableorErrorin ordinary code. You might hide anOutOfMemoryErrororStackOverflowError, after which the program's state can't be trusted. The exception is a top-level safety net in a framework or main loop that logs everything and keeps the process alive. - Respect the checked/unchecked distinction. Checked exceptions burden every caller. Don't use them for logic errors. The reflection API is the classic example of getting this wrong: callers constantly catch exceptions they know can't happen.
- Translate freely. Turn an exception into a more appropriate one for your layer. When parsing a number from a file, catch the
NumberFormatExceptionand throw a subclass ofIOExceptionor your ownMySubsystemException, with the original as the cause.
4. Don't squelch exceptions
The temptation is real. You call a method that might throw a checked exception once a century, the compiler complains, and declaring it would make the compiler complain about every caller of your method too. So you shut it up:
public Image loadImage(String s) {
try {
code that threatens to throw checked exceptions
} catch (Exception e) {
} // so there
}
It compiles, and it runs fine, until the exception actually happens. Then it is silently ignored, the method returns something meaningless, and the failure shows up later, far away, with no clue about its origin. Debugging such a problem can take days.
If an exception matters at all, handle it properly. At the very least:
- declare it and let a caller deal with it;
- wrap it in an unchecked exception (keeping the cause); or
- if ignoring really is correct, say so explicitly:
catch (InterruptedException _) { Thread.currentThread().interrupt(); }, or a comment explaining why it's safe.
An empty catch block without explanation is one of the most reliable signs of a bug. Static analysis tools such as SpotBugs, PMD, Error Prone and the IntelliJ inspections flag it.
5. "Tough love" beats indulgence: throw early
When you detect an error, should you return a dummy value instead of throwing? For example, should pop on an empty stack return null? It's better to throw an exception right at the point of failure than to let a null escape and cause a NullPointerException somewhere else much later, where the connection to the real problem is lost.
Validate arguments at the start of public methods, and fail fast:
void add(String product, int quantity) {
Objects.requireNonNull(product, "product must not be null");
if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive: " + quantity);
. . .
}
Constructors are a prime spot. An object that rejects bad data at construction can never be in an invalid state later. Records make this easy with compact constructors.
6. Propagating exceptions is nothing to be ashamed of
Some programmers feel they must catch every exception they encounter. Call the FileInputStream constructor or readLine, and they reflexively wrap it in try/catch. Often it's much better to pass the exception on:
public void readStuff(String filename) throws IOException {
var in = new FileInputStream(filename);
. . .
}
Higher-level methods are usually better equipped to tell the user about an error or abandon the failed command.
7. Use the standard methods for null and index checks
The Objects class provides ready-made checks that throw the right exception with the library's familiar message:
| Method | Throws if | Exception |
|---|---|---|
requireNonNull(obj), requireNonNull(obj, message), requireNonNull(obj, messageSupplier) | obj is null | NullPointerException |
requireNonNullElse(obj, default) | only if obj and default are both null (otherwise returns obj, or default when obj is null) | NullPointerException |
checkIndex(index, length) | index < 0 or index >= length | IndexOutOfBoundsException |
checkFromToIndex(from, to, length) | the range [from, to) doesn't fit in [0, length) | IndexOutOfBoundsException |
checkFromIndexSize(from, size, length) | the range [from, from + size) doesn't fit in [0, length) | IndexOutOfBoundsException |
Use them for parameter validation:
public void putData(int position, Object newValue) {
Objects.checkIndex(position, data.length);
Objects.requireNonNull(newValue);
. . .
}
The Supplier overload of requireNonNull builds the message only when it's actually needed. That's useful when building the message is expensive.
8. Don't show stack traces to end users
It might seem helpful to show the stack trace to users so they can report it. Don't. Stack traces reveal implementation details that help attackers, such as class names, library versions, file paths and sometimes SQL fragments. The OWASP guidelines list this as information exposure. Users can't do anything with the trace anyway.
Instead, log the full stack trace where developers can retrieve it, and show users a short, friendly message, ideally with a reference number that links the two.
More habits of experienced developers
- Write useful messages. Include the values that matter:
"Index 12 out of bounds for length 10"beats"bad index". Never put passwords, tokens or personal data in messages, since they end up in logs. - Clean up with try-with-resources, not by hand.
- Don't lose the cause when wrapping, and don't log and rethrow at every layer.
- Preserve the interrupt. If you catch
InterruptedExceptionand can't rethrow it, callThread.currentThread().interrupt()so code further up still sees that the thread was interrupted. - Document exceptions with
@throwsin Javadoc, including the important unchecked ones a caller should know about. - Keep exception classes few and meaningful. A small hierarchy per subsystem is plenty. Hundreds of tiny exception classes help nobody.
A complete example
The program below demonstrates the tips:
- tests instead of exceptions;
- one coarse
tryaround a whole task; - translation with a cause;
- squelched versus reported failures;
- fail-fast validation;
- the
Objectsrange checks; - separate messages for users and logs.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// Tip 1: a simple test beats an exception for expected situations
var stack = new ArrayDeque<Integer>(List.of(1, 2));
int popped = 0;
while (!stack.isEmpty()) { stack.pop(); popped++; } // test first
System.out.println("popped " + popped + " without any exception");
Integer next = stack.poll(); // or an API that returns null/Optional
System.out.println("poll on empty deque: " + next);
// Tip 2: one try block around the whole task, not one per statement
System.out.println(saveNumbers(new ArrayDeque<>(List.of(3, 1, 4)), 3));
System.out.println(saveNumbers(new ArrayDeque<>(List.of(3, 1)), 3));
// Tip 3: translate to a meaningful type, keeping the cause
try {
readSetting("timeout=ten");
} catch (ConfigException e) {
System.out.println(e.getMessage() + " (cause: " + e.getCause().getClass().getSimpleName() + ")");
}
// Tip 4: don't squelch -- compare a silent failure with a reported one
System.out.println("squelched: " + loadSquelched("missing.png"));
try {
loadHonest("missing.png");
} catch (IOException e) {
System.out.println("reported: " + e.getMessage());
}
// Tip 5: tough love -- fail at the point of the error, not later
var cart = new Cart();
try {
cart.add(null, 2);
} catch (NullPointerException e) {
System.out.println("rejected at once: " + e.getMessage());
}
// Tip 7: the Objects check methods produce the library's standard messages
int[] data = new int[10];
for (int[] range : new int[][] { { 2, 5 }, { 8, 12 } }) {
try {
Objects.checkFromToIndex(range[0], range[1], data.length);
System.out.println("range " + Arrays.toString(range) + " ok");
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
try {
Objects.checkFromIndexSize(7, 5, data.length);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
// Tip 8: users see a short message; the full trace goes to the log
try {
processOrder("A-42");
} catch (RuntimeException e) {
String incident = "INC-" + Integer.toHexString("A-42".hashCode());
var log = new StringWriter();
e.printStackTrace(new PrintWriter(log));
System.out.println("to the user: Sorry, we couldn't process your order. Reference " + incident);
System.out.println("to the log: " + incident + " " + log.toString().lines().findFirst().orElse(""));
}
}
static String saveNumbers(Deque<Integer> s, int count) {
var out = new StringBuilder();
try {
for (int i = 0; i < count; i++) {
int n = s.pop(); // NoSuchElementException if empty
out.append(n).append(' ');
}
return "saved: " + out.toString().trim();
} catch (NoSuchElementException e) {
return "abandoned after: " + out.toString().trim();
}
}
static int readSetting(String line) throws ConfigException {
String[] parts = line.split("=");
try {
return Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
throw new ConfigException("Bad value for " + parts[0] + ": " + parts[1], e);
}
}
static String loadSquelched(String name) {
try {
return loadHonest(name);
} catch (Exception e) { } // so there -- DON'T
return null;
}
static String loadHonest(String name) throws IOException {
throw new FileNotFoundException("Cannot open image " + name);
}
static void processOrder(String id) {
throw new IllegalStateException("inventory service returned 503 for " + id);
}
}
class ConfigException extends Exception {
private static final long serialVersionUID = 1L;
ConfigException(String message, Throwable cause) { super(message, cause); }
}
class Cart {
private final Map<String, Integer> items = new LinkedHashMap<>();
void add(String product, int quantity) {
Objects.requireNonNull(product, "product must not be null");
if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive: " + quantity);
items.merge(product, quantity, Integer::sum);
}
}
popped 2 without any exception
poll on empty deque: null
saved: 3 1 4
abandoned after: 3 1
Bad value for timeout: ten (cause: NumberFormatException)
squelched: null
reported: Cannot open image missing.png
rejected at once: product must not be null
range [2, 5] ok
Range [8, 12) out of bounds for length 10
Range [7, 7 + 5) out of bounds for length 10
to the user: Sorry, we couldn't process your order. Reference INC-1e3b8a
to the log: INC-1e3b8a java.lang.IllegalStateException: inventory service returned 503 for A-42
Look at the "squelched" line: the caller got null and no hint of what went wrong. The "reported" line names the actual problem.
Common questions
Is it OK to use exceptions for validation of user input?
For input that is usually valid, parsing and catching NumberFormatException is fine and simple. When invalid input is common, as in form validation, check first and collect the errors as data. Throwing hundreds of exceptions per request is slow and makes the logic harder to read.
Should a method return null, Optional or throw?
Return Optional (or an empty collection) when "no result" is a normal outcome, such as a lookup that finds nothing. Throw when the caller broke the contract or the operation failed. Return null only when an existing API style demands it, and document it.
How many custom exception types should a project have? Few. A base exception per subsystem plus a handful of specific subclasses that callers actually distinguish is usually enough. If no caller ever catches a type specifically, it probably doesn't need to exist.
Where should exceptions be logged? Once, at the point where they are finally handled, usually at the top of a request, job or event loop. Lower layers should wrap or propagate them with context, not log them as well, or each failure appears many times in the logs.
Are checked exceptions considered bad practice now? They're debated. Many frameworks avoid them, and they don't work well with lambdas. They are still idiomatic for I/O and other recoverable boundary failures in the JDK. Use them where callers can genuinely recover, and unchecked exceptions elsewhere.
Summary
- Use exceptions only for exceptional situations. Test for expected conditions instead.
- Wrap a whole task in one
tryblock rather than every statement. - Throw and catch precise types. Never catch
ThrowableorErrorin normal code. Don't use checked exceptions for programming errors. - Never swallow an exception silently. Handle, propagate, wrap, or explain.
- Throw early (validate at the point of failure) and catch late (where the program knows what to do).
- Use
Objects.requireNonNull,checkIndex,checkFromToIndexandcheckFromIndexSizefor standard checks. - Log stack traces. Show users only a short message.
Practice Questions
Why is catching an EmptyStackException to detect an empty stack a poor idea, even apart from performance?
An empty stack is a normal, expected state, not an error. Expressing it through an exception hides the program's logic and makes readers think something went wrong. A simple isEmpty() test states the intent directly.
What is wrong with catch (Exception e) {} and what are better alternatives?
It silently discards every exception, including unchecked ones that indicate bugs, so failures surface later with no clue to their cause. Better: declare the exception, handle it meaningfully, wrap it in an unchecked exception with the cause, or, if ignoring it is truly correct, catch the specific type and document why.
Your method receives a null that it can't work with. Should it return a default value or throw?
Usually throw, immediately, for example with Objects.requireNonNull(arg, "arg must not be null"). Returning a dummy value moves the failure to some later point where the cause is hard to find. Only use a default when null is a documented, valid input, for example with Objects.requireNonNullElse.
What does "throw early, catch late" mean?
Detect errors and throw as close to their source as possible, and catch them at the level of the program that knows how to respond, which is usually high up, near the user interface or request handler.
Why shouldn't you display a stack trace to the end user of a web application?
It reveals internal details such as class names, library versions, file paths and possibly data, which helps attackers, and it means nothing to the user. Log it, and show a short message with a reference number.
Which Objects method checks that a sub-range given by a start index and a length fits into an array?
Objects.checkFromIndexSize(from, size, length). For a sub-range given by start and end indexes, use checkFromToIndex(from, to, length).
Previous: Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
Next: Java Assertions: Using assert, Enabling Assertions and Design by Contract
Related reading
- Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
- Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Exceptions: The Exception Hierarchy, Checked and Unchecked
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources

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.