QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Exceptions

Checked and unchecked exceptions, try-with-resources, AssertionError

Checked exceptions (IOException) must be handled or declared with throws, while unchecked ones, subclasses of RuntimeException, need no handling. AssertionError belongs to the Error branch, not Exception, so catch (Throwable) swallows a failed check and the test stays green. try-with-resources closes AutoCloseable resources in reverse order of opening, and an exception from close() is added to the main one as suppressed.

Java · Exceptions

The test is green although the order total is wrong. The check existed, but it was not allowed to fail.

A project has a test that "checks everything": it contains try { … } catch (Throwable t) { t.printStackTrace(); }, because somebody once fought flakiness. The backend started returning a wrong total, but the report has been green for weeks. The CI console shows a stack trace that nobody reads. The test did not find the defect because it swallowed it itself.

This lesson covers how the exception hierarchy is built, why AssertionError lies in another branch, what checked and unchecked mean, how try-with-resources works and where in test code catching an exception is appropriate and where it is not.

How it works and why it is designed so

Everything that can be thrown inherits Throwable, and then the branches diverge by purpose. Error marks serious failures of the runtime environment (OutOfMemoryError, StackOverflowError) that a program usually does not handle. This is where AssertionError belongs: assert libraries throw it, and JUnit's AssertionFailedError and AssertJ's exception are its descendants. The idea is that a failed check is not a situation the code should "handle" and move on from; it must reach the runner. Exception is what can be handled.

Where assertions and exceptions sit in the hierarchy

ThrowableErrorusually not caughtExceptioncan be handledAssertionErrorassert librariesOutOfMemoryErrorJVM failureIOExceptionchecked: must handleRuntimeExceptionunchecked: NPE, IAE
Figure 1. AssertionError lies in the Error branch, so catch (Exception) does not see it.

The Exception branch has two kinds. Checked ones (IOException, SQLException) the compiler forces you to handle or declare with throws: this is meant for failures that can happen even in a correct program (no file, a dropped connection). Unchecked ones are descendants of RuntimeException (NullPointerException, IllegalArgumentException, IndexOutOfBoundsException): usually a programming error, handling is optional. Selenium exceptions, including NoSuchElementException, TimeoutException and StaleElementReferenceException, are also unchecked: they inherit WebDriverException, which is a RuntimeException.

Example: from a "green" test to an honest one

@Test
void orderTotalIsCorrect() {
    try {
        Order order = api.createOrder(cart);
        assertEquals(new BigDecimal("100.00"), order.total());
    } catch (Throwable t) {
        t.printStackTrace();     // the AssertionError is swallowed, the test is green
    }
}

Diagnosis: catch (Throwable) also catches AssertionError, so a failed check never reaches JUnit. The cure: remove the try/catch altogether. If a test needs to catch an exception, only an expected and specific one. If catch (Exception) is written, the AssertionError will not be caught (it is not an Exception) and the test will fail as it should; but such "wrapping" still hides the real cause of other exceptions.

An expected failure is checked not through try/catch with fail() (there fail() itself throws an AssertionError, which is easy to swallow) but through dedicated methods:

// JUnit 5: assertThrows returns the exception for further checks
IllegalArgumentException ex = assertThrows(
        IllegalArgumentException.class, () -> new Order(-1));
assertEquals("amount must be positive", ex.getMessage());

// AssertJ: a chain of checks on the same exception
assertThatThrownBy(() -> new Order(-1))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessageContaining("positive");

Custom exceptions and the cause

For test code custom exceptions are usually made unchecked, so that helper signatures are not cluttered: class TestDataException extends RuntimeException. The main rule: pass the cause to the constructor. Then the report has a "Caused by" with the original stack. If you write new TestDataException(e.getMessage()), the root-cause stack is lost and the failure has to be investigated blindly.

static User loadUser(Path file) {
    try {
        return MAPPER.readValue(Files.readString(file), User.class);
    } catch (IOException e) {
        throw new TestDataException("Cannot load test data: " + file, e); // with the cause
    }
}

A checked exception cannot be thrown from a lambda in a Function or Runnable, because their methods do not declare throws. In a stream it is wrapped into an unchecked one: UncheckedIOException for IOException or a custom exception with the cause. But InterruptedException must not be swallowed: if you catch it, restore the flag (Thread.currentThread().interrupt()) and throw on, otherwise a thread that was asked to stop will not notice.

try-with-resources

The construct calls close() on every resource that implements AutoCloseable (streams, database connections, clients), even if the body threw an exception. Closing goes in the reverse order of opening. If both the body and close() throw, the body's exception stays the main one and the closing exception is attached to it as suppressed (getSuppressed()). In a classic finally the second exception would erase the first.

int countOrders(String url, String user, String pass) throws SQLException {
    try (var conn = DriverManager.getConnection(url, user, pass);
         var st = conn.createStatement();
         var rs = st.executeQuery("select count(*) from orders")) {
        rs.next();
        return rs.getInt(1);
    }   // closing order: rs, then st, then conn
}

A resource can also be a reference to an already created variable (Java 9+), if it is final or effectively final: try (conn) { … }. A browser driver lives longer than one block of code and is shared between the steps of a test, so it is closed with quit() in @AfterEach rather than in try-with-resources.

Limits and alternatives

  • Catch an exception when you can really react: repeat an action on an unstable element (StaleElementReferenceException), add context and rethrow, handle an expected negative scenario. A retry is done only for a specific exception and with a limited number of attempts; an AssertionError is never retried "for luck".
  • Cleanup in finally is safe, while a return or throw in finally hides the current exception.
  • A test method with throws Exception is acceptable (JUnit allows it) and better than an empty catch. But in helpers called from many places throws Exception merely moves the problem to all callers.
  • To check several conditions in one run there are AssertJ soft assertions and JUnit assertAll: they collect several failures without needing try/catch.

Common mistakes

  • An empty catch or just printStackTrace(): the failure disappears, the test is green and the scenario was not executed.
  • catch (Throwable) around checks: the AssertionError is swallowed.
  • Losing the cause: throw new X(e.getMessage()) instead of throw new X("…", e).
  • Importing the wrong class: java.util.NoSuchElementException instead of org.openqa.selenium.NoSuchElementException means the catch does not fire on a Selenium exception.
  • try/catch with fail() instead of assertThrows or assertThatThrownBy.

Check yourself

Why does a test with catch (Throwable t) { t.printStackTrace(); } around assertEquals stay green, while with catch (Exception e) it does not?

Answer

AssertionError belongs to the Error branch, not Exception. catch (Throwable) catches and swallows it, while catch (Exception) lets it through, so it reaches the runner.

In try (A a = open(); B b = open()) the body threw an exception and b.close() threw too. Which exception will the test see and in what order were the resources closed?

Answer

The test sees the body's exception, and the one from b.close() is in getSuppressed(). b is closed first, then a: the reverse of opening.

How does throw new TestDataException(e.getMessage()) differ from throw new TestDataException("Cannot load " + file, e)?

Answer

The second keeps the cause: the report shows "Caused by" with the root-cause stack and context (which file). In the first the original exception's stack is lost.

In an interview. Junior: Everything throwable inherits Throwable. The compiler forces handling of checked exceptions, not of unchecked ones (RuntimeException). try-with-resources closes resources itself. I do not write an empty catch in tests. Middle/Senior: I know that AssertionError is an Error, so catch (Throwable) hides failed checks, and I verify expected failures through assertThrows or assertThatThrownBy. I make custom exceptions unchecked and always with a cause. I catch an exception only when I can react (a bounded retry on a specific exception) and I do not swallow InterruptedException.

More articles in this chapter