Coding⏱️ 1 min read📅 2026-05-31

How to Fix: How do you assert that a certain exception is thrown in JUnit tests?

Assert that a certain exception is thrown in JUnit tests using @Test and @Throwing

Quick Answer: Use the @Test annotation with @Throwing to assert that an exception is thrown.

To assert that a certain exception is thrown in JUnit tests, you can use the @Throws annotation on your test method.

🛠️ Step-by-Step Verified Fixes

Method 1: Using @Throws Annotation

  1. Step 1: Annotate your test method with @Test and add the @Throws annotation.

Example Code:

@Test
@Throws(IndexOutOfBoundsException.class)
public void testFooThrowsIndexOutOfBoundsException() {
foo.doStuff();
}

This will ensure that the testFooThrowsIndexOutOfBoundsException method is executed only if an IndexOutOfBoundsException is thrown by the code being tested.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions