We check exception type hierarchy to make sure the right kind of error happens. This helps us catch mistakes early and fix them.
Checking exception type hierarchy in 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.
FileNotFoundException is a subclass of IOException.assertThrows(IOException.class, () -> {
throw new FileNotFoundException();
});NullPointerException is a subclass of RuntimeException.assertThrows(RuntimeException.class, () -> {
throw new NullPointerException();
});IllegalArgumentException is a subclass of Exception.assertThrows(Exception.class, () -> {
throw new IllegalArgumentException();
});IllegalArgumentException is NOT a subclass of IOException.assertThrows(IOException.class, () -> {
throw new IllegalArgumentException();
});The first test passes because FileNotFoundException is a subclass of IOException. The second test fails because IllegalArgumentException is not related to IOException.
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"); }); } }
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.
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.