Testing expected exceptions in JUnit means asserting that a specific piece of code throws the exception you expect, rather than letting an uncaught exception simply fail the test for the wrong reason.
For a method that validates a non-negative deposit amount, assertThrows(IllegalArgumentException.class, () -> account.deposit(-5)) confirms a negative deposit correctly throws.
@Test
void rejectsNegativeDeposit() {
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> account.deposit(-5));
assertEquals("Amount must be positive", ex.getMessage());
}A concise interview answer is
In JUnit 5 I use assertThrows(ExceptionType.class, () -> code) to assert a specific block throws the expected exception, and I can inspect the returned exception's message afterward. It's more precise than JUnit 4's @Test(expected=...) because it scopes the expectation to one exact call.
Last updated: 16 July 2026
Previous question: Explain the difference between @Before and @BeforeClass. How are they used?
Next question: What is the difference between assertEquals, assertTrue, and assertSame in JUnit?