How to generate custom exception in selenium and Java

We can create custom exceptions in Selenium with Java to make error handling more meaningful and user-friendly. Default exception messages are often unclear, so by creating a custom exception class that extends the Exception class, we can provide clear and descriptive error messages.

Custom exceptions make debugging in Selenium automation easier since they display specific messages that help identify the exact issue. After catching a standard exception, we can throw our custom exception using the super keyword to pass the custom message to the parent Exception class.

This approach improves code readability, error tracking, and maintainability in Selenium test automation.

The following is an example script to print a custom exception message in Selenium using Java.
In this example, we have created a class named CustomMessage and intentionally failed the test using Assert.fail() to demonstrate custom exception handling. When the exception is caught, we call the CustomException class.

The CustomException class extends the built-in Exception class using inheritance and calls the parent class constructor with the super keyword to pass the custom message. This approach helps us display meaningful and user-defined error messages, improving the clarity and debugging process in Selenium test automation.

Example Script:

package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class CustomMessage {
WebDriver driver = null;
@Test
public void customMessage() throws CustomExeption {
try {
driver = new ChromeDriver();
driver.get(“https://google.com”);

  Assert.fail("Intentionally failed");
  }
  catch(AssertionError er) {
      throw new CustomException("An error occured in home page");
  }

}
}

CustomException Class :

package tests;

public class CustomException extends Exception{

public CustomException(String message) {

super(message);

}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x