Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

What is wrong with this test, and how would you write it with assertThrows?

Java
try {
service.withdraw(-5);
fail();
} catch (IllegalArgumentException e) { }

The try-fail-catch test is verbose and easy to get wrong: the catch block is empty, so it asserts nothing about the exception, and it is easy to catch too broad a type or to forget the fail() call so the test passes when nothing is thrown. In JUnit 5 we write IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> service.withdraw(-5)); and then assert on e.getMessage(). assertThrows also passes for subclasses of the expected type, while assertThrowsExactly requires the exact class.

Why this question is asked

Testing that code rejects bad input is as important as testing that it accepts good input, and the old way of doing it hides several bugs inside the test itself. Interviewers show this snippet because it is common in older code bases and because the improvement shows whether we know the modern assertion API and its small but important details. In this answer, we will see what is wrong with the original test, rewrite it with assertThrows, check the exception's message, and look at the difference between assertThrows and assertThrowsExactly.

1What the Original Test Does

Here is the test from the question, laid out properly. The idea is that withdraw(-5) should throw IllegalArgumentException. If it does, the catch block swallows it and the test passes. If it does not throw, the next line, fail(), makes the test fail.

Java
@Test void rejectsNegativeAmount() {
try {
service.withdraw(-5);
fail(); // fails the test if no exception was thrown
} catch (IllegalArgumentException e) {
// empty: we expected this
}
}

It works in the simple case, but it has several problems. It takes seven lines to say one thing. The empty catch block checks nothing about the exception: if withdraw throws IllegalArgumentException for a completely different reason, say a missing account number, the test still passes. And the pattern is fragile when someone edits it.

2How the Pattern Goes Wrong

The most common mistake is forgetting fail(). Then the test passes whether or not an exception is thrown, so it tests nothing. Another is catching too broad a type. If someone changes the catch to Exception, or to Throwable, the test passes for any exception at all, including a NullPointerException caused by a bug. Worst of all, catching AssertionError or Throwable also catches the AssertionFailedError that fail() throws, so the test can never fail.

Java
try {
service.withdraw(-5);
fail("expected an exception");
} catch (Throwable t) { // too broad: this also catches the error thrown by fail()
// empty
}
// The test passes even when withdraw(-5) succeeds

Each of these bugs makes a test that stays green while the code is wrong, which is the most dangerous kind of test, because it gives false confidence.

3Rewriting It With assertThrows

assertThrows takes the expected exception class and an Executable, a lambda containing the code that should throw. It runs the lambda. If the lambda throws an exception of the expected type, assertThrows returns it. If the lambda throws nothing, or throws a different type, the assertion fails with a clear message.

Java
@Test void rejectsNegativeAmount() {
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> service.withdraw(-5));
assertEquals("amount must be positive: -5", e.getMessage()); // passes
}
// If withdraw(-5) does not throw:
// org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
Step throughWhat assertThrows checks
  1. Run the lambda
  2. Did it throw?
    YesCheck the typeNoFail: nothing was thrown
  3. Is it the expected type or a subclass?
    YesReturn the exceptionNoFail: unexpected exception type
  4. Assert on the returned exceptionmessage, cause, error code

4 steps in order. Play them, or step through them one at a time.

Notice that the test is now shorter and stricter. Because assertThrows returns the exception, we can check the message, the cause, or a custom field such as an error code. That second assertion is what proves the exception came from the rule we meant to test. It is a good habit to keep only the call that should throw inside the lambda; if the lambda also contains setup code, an exception from the setup could satisfy the assertion by accident.

4AssertThrows Against assertThrowsExactly

assertThrows passes when the thrown exception is the expected type or any subclass of it. That is usually what we want, but sometimes it is too loose. NumberFormatException, for example, is a subclass of IllegalArgumentException, so a test expecting IllegalArgumentException also passes when parsing fails somewhere inside withdraw. assertThrowsExactly, added in JUnit 5.8, requires the thrown class to be exactly the expected one.

Java
assertThrows(IllegalArgumentException.class,
() -> Integer.parseInt("abc")); // passes: NumberFormatException is a subclass
assertThrowsExactly(IllegalArgumentException.class,
() -> Integer.parseInt("abc")); // fails: the type is NumberFormatException

So we use assertThrows when any exception from a family is acceptable, and assertThrowsExactly, or a check on the message or a custom exception type, when the exact cause matters. For domain errors, a dedicated exception such as InsufficientFundsException makes tests clearer than a generic IllegalArgumentException.

5Follow-up questions

What about JUnit 4's @Test(expected = ...)?

It is gone in JUnit 5. It also had a weakness: the exception could come from any line in the test, including setup, so the test could pass for the wrong reason. assertThrows limits the expected exception to the lambda and returns it so we can inspect it.

How do I assert that code does not throw?

Simply call it; any unexpected exception fails the test. If we want to make the intent explicit, assertDoesNotThrow(() -> service.withdraw(5)) does that, and its overload with a ThrowingSupplier returns the result so we can assert on it too.

Can I test checked exceptions this way?

Yes. The Executable lambda is allowed to throw any Throwable, so assertThrows(IOException.class, () -> reader.read(path)) compiles without a try block.

6Conclusion

In this answer, we saw that the try-fail-catch pattern is long, checks nothing about the exception, and breaks silently when fail() is forgotten or the catch is too broad. assertThrows replaces it with one call that fails clearly when nothing or the wrong type is thrown, and returns the exception so we can assert on its message. It accepts subclasses, while assertThrowsExactly demands the exact type.

What to say in the interviewAbout 70 seconds aloud

Open with

The try-fail-catch version works in the happy case, but it is verbose and fragile. The catch block is empty, so it checks nothing about the exception; if withdraw throws IllegalArgumentException for some other reason, the test still passes.

Then, if they want more

It is also easy to break: if someone forgets fail(), the test passes even when nothing is thrown, and if someone widens the catch to Throwable, it even swallows the error that fail() throws.

In JUnit 5 I would write IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> service.withdraw(-5)); and then assertEquals on e.getMessage(), for example that the amount must be positive. assertThrows fails with a clear message if nothing is thrown or the type is wrong, and because it returns the exception I can check the message, cause or error code, which proves it came from the rule I meant to test.

I keep only the call that should throw inside the lambda. One detail is that assertThrows also passes for subclasses, so a NumberFormatException satisfies an IllegalArgumentException check. When the exact type matters, I use assertThrowsExactly, which was added in JUnit 5.8, or I throw a dedicated domain exception.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is wrong with this test, and how would you write it with assertThrows?": https://scrivio-interview-library.netlify.app/java/junit/ae0e7e33e3/