Code Quality: Clean Code in Java ·
‹ Previous Next ›
⏱ 6 min read Modified: 2026-12-05

Clean Error Handling and Unit Tests in Java

The method below reports «not found» with the value -1. The caller forgets to check it, and the program fails twenty lines later with an exception that says nothing about users:

static final List<String> USERS = List.of("anna", "bob", "carol");

static int findUser(String login) {
    return USERS.indexOf(login); // -1 if not found
}

int index = findUser("dave");
// ... twenty lines later
String user = USERS.get(index);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3

Clean error handling makes failures impossible to ignore and easy to diagnose: errors are reported with exceptions that carry context, not with special return values, and methods never hand out null where a caller expects a value or a collection. Clean tests are the other safety net: small, independent, readable tests that let you refactor code without fear. This lesson covers both from the clean code point of view; the general rules of Java exception handling are in Exception Handling Best Practices.

Exceptions instead of error codes

An error code is a return value that means failure: -1, false, null or an int status. It mixes the normal result with the error, forces every caller to check it immediately, and when a check is forgotten the program keeps running in a wrong state, as in the example above.

An exception separates the two paths. The happy path reads straight through, and the failure cannot be lost silently:

static String findUser(String login) {
    if (!USERS.contains(login)) {
        throw new UserNotFoundException("No user with login '" + login + "'");
    }
    return login;
}

When «not found» is a normal answer rather than an error, a method can return Optional instead: Optional<User> findUser(String login). The type tells the caller that the value may be missing, and the compiler will not let them use it as a User without deciding what to do. Use exceptions for situations the caller does not expect, and Optional for an empty result that is part of the contract.

Exceptions with context

An exception message should let you understand the failure from the log alone, without reproducing it: which operation failed, for which input, and why. «Error» or «Invalid data» forces someone to attach a debugger to production.

throw new IllegalStateException("Error");

throw new IllegalStateException(
        "Cannot ship order " + order.id() + ": status is " + order.status() + ", expected PAID");

When you translate a low-level exception into one of your own types, pass the original as the cause so the stack trace keeps the full chain: throw new PaymentException("Payment for order " + id + " failed", e). Details on wrapping and logging are in Wrapping an exception and keeping the cause.

Checked or unchecked: what Clean Code says

Robert C. Martin’s book Clean Code recommends unchecked exceptions. The argument is about coupling: when a low-level method adds a checked exception to its signature, every method on the call path up to the handler must change its throws clause, so a detail of the lowest layer leaks into all the layers above it.

Java itself takes a more balanced position. Checked exceptions are useful when the caller can and should recover — a missing file, a refused connection — and the JDK uses them that way (IOException, SQLException). Most modern frameworks, including Spring and JPA, wrap these into unchecked exceptions, and checked exceptions do not work with lambdas and streams without extra code. A reasonable rule for application code: use unchecked exceptions for programming errors and broken invariants, consider checked ones for recoverable conditions at the boundary of your system. The full comparison is in Checked vs unchecked exceptions: when to use which.

Whatever you choose, do not list unchecked exceptions in a throws clause just for decoration (throws IllegalArgumentException); document them with the Javadoc @throws tag instead.

Don't return null, don't pass null

Returning null pushes a check onto every caller, and the first caller who forgets it gets a NullPointerException far from the place where the null came from. For collections there is always a better answer: an empty collection.

static List<Order> findOrders(String customer) {
    if (customer.isBlank()) {
        return null;
    }
    return List.of(new Order("A-1"));
}

for (Order order : findOrders(" ")) {   // NullPointerException
    System.out.println(order.id());
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because the return value of "NullCollection.findOrders(String)" is null

Since Java 15 the message at least names the method that returned null. Returning List.of() instead makes the loop simply do nothing, and every caller is correct without a check. For a single value that may be absent, return Optional; for a missing configuration or a broken invariant, throw an exception with a message.

Passing null as an argument is just as bad: the method either has to check every parameter or crash somewhere inside. Reject it at the entrance with Objects.requireNonNull(customer, "customer"), and do not design APIs where null means «use the default» — add an overload without that parameter instead.

Tidy handlers: multi-catch and try-with-resources

Error-handling code is still code, and it should be as short and readable as the rest. Two language features remove most of the boilerplate: multi-catch for identical handlers and try-with-resources for closing resources.

try {
    importFile(path);
} catch (NoSuchFileException | AccessDeniedException e) {
    log.warn("Cannot read {}: {}", path, e.toString());
}

try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.lines().filter(line -> !line.isBlank()).count();
}

Never leave a catch block empty: a swallowed exception turns a failure into silence. How each construct works is explained in try-catch: multi-catch and Try-with-resources in Java.

Test code is production code

Unit tests deserve the same care as the code they test: clear names, no duplication, small methods. Dirty tests are hard to change, so they get disabled or deleted when the code changes, and the code loses its safety net exactly when it is needed for refactoring.

Three habits keep a test suite useful:

  • Change the tests together with the code. A test that no longer describes the behavior is worse than no test, because it gives false confidence.
  • Check one concept per test method. When shouldCalculateTax fails, you know what broke; when testEverything fails, you start debugging.
  • Cover the paths that matter: the normal case, the boundaries (empty list, zero, maximum) and the error cases.

Given, when, then

A readable test has three parts: given prepares the data, when runs the operation under test, and then checks the result. The same structure is known as Arrange-Act-Assert. Marking the parts with comments or blank lines lets a reader find the essential line of the test at a glance.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.math.BigDecimal;
import org.junit.jupiter.api.Test;

class CartTest {

    @Test
    void totalIncludesAllItems() {
        // given
        Cart cart = new Cart();
        cart.add(new Item("Book", new BigDecimal("12.50")));
        cart.add(new Item("Pen", new BigDecimal("1.20")));

        // when
        BigDecimal total = cart.total();

        // then
        assertEquals(new BigDecimal("13.70"), total);
    }

    @Test
    void addingItemWithNegativePriceIsRejected() {
        Cart cart = new Cart();

        assertThrows(IllegalArgumentException.class,
                () -> cart.add(new Item("Refund", new BigDecimal("-5.00"))));
    }
}

The test names describe behavior, not methods: totalIncludesAllItems stays correct even if total() is renamed, and a failing test reads like a broken requirement. JUnit 5 also accepts @DisplayName for a sentence with spaces.

F.I.R.S.T. principles of unit tests

F.I.R.S.T. is a checklist of five properties of good unit tests. A test suite that has all five is run often, trusted when it is green and taken seriously when it is red.

Letter Meaning What breaks it
Fast The whole unit test suite runs in seconds, so developers run it after every change Real database, network calls, Thread.sleep()
Independent Tests do not depend on each other and pass in any order, alone or together Shared static state, one test preparing data for the next
Repeatable The same result on any machine, any time, without network LocalDate.now(), random values, time zones, file paths of one machine
Self-validating The test passes or fails by itself, nobody reads the output Tests that only print results with System.out
Timely Tests are written together with the code, ideally just before it (test-driven development) Tests added weeks later to code that was not designed to be testable

The Repeatable row is where most flaky tests come from. Code that calls LocalDate.now() directly cannot be tested for «the last day of the month» on any other day. Pass a java.time.Clock into the class and use Clock.fixed(...) in the test, and the date becomes test data like any other.

Frequently Asked Questions

Should a method return null or an empty list when nothing is found?

An empty list. Callers can loop over it, stream it and ask for its size without a null check, and nothing breaks if someone forgets about the empty case. Return List.of() or Collections.emptyList(). More in Don't return null, don't pass null.

Is it bad to use exceptions for validation errors?

No, if the invalid input is unexpected for the method, as with an illegal argument. For user input that is often invalid, such as a form, it is cleaner to collect validation errors into a result object and show them all at once, and keep exceptions for real failures.

How many assertions can one unit test have?

As many as one concept needs. Checking several fields of the same result object is one concept; checking the total and then also the discount logic and the tax rules in one method is three tests. JUnit 5 assertAll() reports every failed assertion of a group at once.

Do I have to write tests before the code?

It is not mandatory, but tests written early, or right before the code as in test-driven development, push the design towards small methods and injected dependencies. Tests written much later often reveal code that is hard to test and has to be changed first.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.