0
0
JUnittesting~5 mins

Why exception testing validates error handling in JUnit

Choose your learning style9 modes available
Introduction

Exception testing checks if your program correctly handles errors. It makes sure your code reacts safely when something goes wrong.

When you want to confirm your code throws the right error for bad input.
When you need to check that your program does not crash unexpectedly.
When you want to verify that error messages are clear and helpful.
When testing how your code behaves with missing or invalid data.
When ensuring your program recovers or stops safely after an error.
Syntax
JUnit
@Test
void testMethod() {
    assertThrows(ExpectedException.class, () -> {
        // code that should throw the exception
    });
}

Use assertThrows to check if a specific exception is thrown.

The lambda inside assertThrows contains the code expected to fail.

Examples
This test checks that dividing by zero throws an ArithmeticException.
JUnit
@Test
void testDivideByZero() {
    assertThrows(ArithmeticException.class, () -> {
        int result = 10 / 0;
    });
}
This test verifies that calling a method on null throws a NullPointerException.
JUnit
@Test
void testNullPointer() {
    String text = null;
    assertThrows(NullPointerException.class, () -> {
        text.length();
    });
}
Sample Program

This test checks that the divide method throws an ArithmeticException when dividing by zero. It confirms the error handling works as expected.

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

public class CalculatorTest {

    @Test
    void testDivideByZeroThrows() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, () -> {
            calc.divide(10, 0);
        });
    }
}

class Calculator {
    public int divide(int a, int b) {
        return a / b;
    }
}
OutputSuccess
Important Notes

Always test for exceptions to catch bugs early and improve program safety.

Use clear exception types to make tests easy to understand.

Summary

Exception testing ensures your code handles errors properly.

Use assertThrows in JUnit to check for expected exceptions.

This helps prevent crashes and improves user experience.