0
0
JUnittesting~5 mins

Checking exception type hierarchy in JUnit

Choose your learning style9 modes available
Introduction

We check exception type hierarchy to make sure the right kind of error happens. This helps us catch mistakes early and fix them.

When you want to test if a method throws a specific exception or its subclass.
When you want to ensure your code handles errors correctly in a chain of exceptions.
When you want to verify that a general exception type is thrown instead of a more specific one.
When you want to confirm that your code does not throw unexpected exceptions.
When you want to document expected error behavior in your tests clearly.
Syntax
JUnit
assertThrows(ExpectedException.class, () -> {
    // code that should throw exception
});

assertThrows checks if the code throws the expected exception or any subclass of it.

The first argument is the exception class you expect.

Examples
This test passes because FileNotFoundException is a subclass of IOException.
JUnit
assertThrows(IOException.class, () -> {
    throw new FileNotFoundException();
});
This test passes because NullPointerException is a subclass of RuntimeException.
JUnit
assertThrows(RuntimeException.class, () -> {
    throw new NullPointerException();
});
This test passes because IllegalArgumentException is a subclass of Exception.
JUnit
assertThrows(Exception.class, () -> {
    throw new IllegalArgumentException();
});
This test fails because IllegalArgumentException is NOT a subclass of IOException.
JUnit
assertThrows(IOException.class, () -> {
    throw new IllegalArgumentException();
});
Sample Program

The first test passes because FileNotFoundException is a subclass of IOException. The second test fails because IllegalArgumentException is not related to IOException.

JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionHierarchyTest {

    @Test
    void testFileNotFoundExceptionIsIOException() {
        assertThrows(IOException.class, () -> {
            throw new FileNotFoundException("File missing");
        });
    }

    @Test
    void testIllegalArgumentExceptionIsNotIOException() {
        assertThrows(IOException.class, () -> {
            throw new IllegalArgumentException("Bad argument");
        });
    }
}
OutputSuccess
Important Notes

Use assertThrows to check exception types and their subclasses easily.

If the thrown exception is not the expected type or subclass, the test fails with a clear message.

This helps catch errors early and documents expected error behavior in your tests.

Summary

assertThrows checks if code throws an expected exception or its subclass.

Tests pass if the thrown exception matches or inherits from the expected type.

Tests fail if a different exception type is thrown.