0
0
JUnittesting~5 mins

assertThrows for exceptions in JUnit

Choose your learning style9 modes available
Introduction

We use assertThrows to check if a piece of code correctly throws an error when something goes wrong. This helps us catch mistakes early.

When you want to make sure your code stops and shows an error for bad input.
When testing if a method throws an exception for invalid operations.
When you want to confirm that your program handles errors as expected.
When you want to avoid crashes by verifying error handling.
When writing tests to improve code safety and reliability.
Syntax
JUnit
assertThrows(ExpectedException.class, () -> {
    // code that should throw the exception
});

The first argument is the type of exception you expect.

The second argument is a lambda with the code that should throw the exception.

Examples
This test checks if parsing a non-number string throws a NumberFormatException.
JUnit
assertThrows(NumberFormatException.class, () -> {
    Integer.parseInt("abc");
});
This test checks if calling a method on null throws a NullPointerException.
JUnit
assertThrows(NullPointerException.class, () -> {
    String s = null;
    s.length();
});
Sample Program

This test checks if dividing by zero throws an ArithmeticException. The test passes if the exception is thrown.

JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

public class ExceptionTest {

    @Test
    void testDivideByZero() {
        assertThrows(ArithmeticException.class, () -> {
            int result = 10 / 0;
        });
    }
}
OutputSuccess
Important Notes

If the code does not throw the expected exception, the test will fail.

You can capture the thrown exception by assigning the result of assertThrows to a variable.

Use assertThrows to make your tests clear and focused on error handling.

Summary

assertThrows checks if code throws the right exception.

It helps catch errors and improve code safety.

Use it with a lambda to test error cases simply.