How to handle Expected Exceptions in Selenium using TestNG?

There is a great kind of relationship between normal execution flow and Exception as Developer and Tester. It’s a very famous saying that Exception exists everywhere, so it exists in programming too. We know some of the Expected Exceptions in a particular logic like Arithmetic Exception occurs when we divide an integer by zero. Hence, when there are chances of getting some expected exceptions then we can handle it with exception handling technique either by try-catch or by throwing a custom exception.

We already have some of the detailed articles on Exceptions and Exception handling. Click on the link below to go through the tutorials on Exceptions and its handling:

These tutorials are the fundamental tutorials, which will introduce you to some of the major exceptions which generally occur while developing automation scripts in Selenium with Java. Also, they teach you the techniques to handle such unexpected and expected exceptions.

Here are some of the recommended TestNG tutorials for you:

If you have gone through above tutorials on Exception handling, you must have noticed that Java inbuilt techniques used to handle exceptions in Selenium. Today we will learn one of the most important features of the TestNG which helps in auto handling expected exceptions in our selenium automation project.

How to handle expected exceptions in Selenium using TestNG?

Let’s look at the general program in which we are storing the value in String array at the index which already has the NULL value or simply index does not exist. So here is the program below:

After running the above program, we get ArrayIndexOutOfBoundsException. We can say that this is one of the expected exceptions when we are storing data after the index ends in an array. Here is the console output.

Failed with expected Exceptions

Once we have identified the expected exception then we can handle it properly. We can handle the above scenario with try and catch. Let’s look at the program which handled exception using try and catches block.

Exception handling using Try & Catch

In this scenario, the test will be passed but catch will handle the exception.

Passed Try catch expected Exceptions

Expected exceptions handling with TestNG

This is the today’s agenda. Now we will see how we can handle the exception using TestNG inbuilt feature. Let’s look at the declaration part:

Below is the sample program which uses the above statement and handles ArrayIndexOutOfBoundsException.

Passed with expected Exceptions

We have seen exception handling with TestNG and Try catch as well. You can post your queries below and don’t miss to join our group for more updates.

Join Inviul fb group


Leave a Reply