@Test annotation attributes – expectedExceptions attribute

In this post, we will discuss the expectedExceptions attribute in TestNG.

What does the expectedExceptions attribute do? Sometimes, in our test cases, we need to verify whether certain exceptions have occurred. This attribute will help us achieve that. It would take an array of exception classes and check whether that exception has occurred or not.
But, if any of the listed exceptions don’t occur, it will fail that test.


expectedExceptions will take a string of exception classes as shown below –

@Test(expectedExceptions = {IOException.class, ArithmeticException.class}) 

Now, we will write three test cases –

  • test1 – this will use expectedExceptions = { IOException.class, ArithmeticException.class } and will throw the IOException, which is a part of listed exceptions.
  • test2 – this will also use expectedExceptions = { IOException.class, ArithmeticException.class } but will not throw any exception.
  • test3 – this will also use expectedExceptions = { IOException.class, ArithmeticException.class }, but will throw an ArrayIndexOutOfBoundsException, which is not part of the listed exceptions
import java.io.IOException;
import org.testng.annotations.Test;

public class CodekruTest {

	// this test will pass
	@Test(expectedExceptions = { IOException.class, ArithmeticException.class })
	public void test1() throws IOException {
		System.out.println("test1 throwing an IOException");
		throw new IOException();

	// this test will fail
	@Test(expectedExceptions = { IOException.class, ArithmeticException.class })
	public void test2() {
		System.out.println("test2 not throwing an exception");

	// this test will also fail
	@Test(expectedExceptions = { IOException.class, ArithmeticException.class })
	public void test3() {
		System.out.println("test3 throwing an ArrayIndexOutOfBoundsException");
		throw new ArrayIndexOutOfBoundsException();


Output –

test1 throwing an exception
test2 not throwing an exception
test3 throwing an exception
PASSED: test1
FAILED: test2
FAILED: test3

    Default test
    Tests run: 3, Failures: 2, Skips: 0
  • test1() passed because the exception thrown matches one of the exceptions present in the expectedExceptions list.
  • test2() failed because no exceptions were thrown, and it was expected that one of the listed expectedExceptions should have been thrown.
  • test3() failed because a different exception type was thrown, not listed in the expectedExceptions list.

We hope that you have liked the article. If you have any queries or doubts, please feel free to write us in the comments or mail us at admin@codekru.com.

Other @Test attributes
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *