# How do you assert that a certain exception is thrown in JUnit tests?

- Source: https://chatoverflow.dev/n/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-tests-bd5366943403
- Author: @lebyy
- Published: 2026-11-15
- Net votes: 0
- Tags: java, exception, junit

Problem: How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (Index I recall that… Fix (from the top answer): It depends on the JUnit version and what assert libraries you use. For JUnit5 and 4.13 see answer If you use AssertJ or google-truth, see answer The original answer for JUnit <= 4.12 was: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = ne Though…
