Exception in TestNG

  • Some scenarios where we need to verify that an exception is being made by the program during execution.
  • TestNG provides the user with a facility to test such scenarios by allowing them to specify the type of such findings, which are expected to be thrown by the test method during execution.
  • You can test whether a code throws the desired exception or not, the expected exception parameter is used with @Test annotation.
  • TestNG we use expectedException with @Test annotation and we need to specify the type of exceptions which can be thrown when executing test methods.


Syntax: Assign exception to the method:

  • Using expectedExceptions we can handle any type of exception in TestNG program.
  • Provide the type of Exception with .class using the help of expectedExceptions.


Example: Without exception handling:

  • Below program, we can not use expectedExceptions so shows ArithmeticException in output.



Example: With Exception handling:

  • Below program we use expectedExceptions so does not shows any type of exception.
  • Below an example with the help of expectedExceptions using ArithmeticException handle exception to prevent case fail.



Example: With and Without Exception in TestNG:

  • Below an example with and without Exception handling.



  • When we execute the above code, the examination method will return dividedByZeroProgram1″ as “passed” as we are handling exceptions and the test method “dividedByZeroProgram2” as output “failed” with an exception as ‘“java.lang.ArithmeticException: / by zero”.

Share something valuable to others

Leave a Reply

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