Selenium

How to Manage the Expected Conditions in Selenium

Errors arrive unexpectedly and can disrupt the normal flow of execution. This is something that every programmer or tester faces at one point or the other while coding and testing. The main motto of the testers is to debug the error and resolve it. In this article, we will understand what exceptions are in Selenium and how to handle them. After that, we will see an overview of the exception’s hierarchy. We will also talk about the types of exceptions and the difference between the checked and unchecked exceptions, and the basic syntax of handling.

What Is Exception Handling?

An exception is an occurrence during a programmed execution which prevents the instructions from following the program’s regular flow. To put it the other way, anything that causes your test case to stop while it’s running is known as an exception. When one happens, the application halts and an exception object is produced. After an exception is raised, the program searches for someone to handle it. Much debugging information is provided by the exception object including the method hierarchy, the line number where the exception occurred, the type of the exception, and more. As a result, you will see the various errors while working with the Selenium WebDriver depending on the code that you write. Sometimes, the same code functions well while others don’t. When you run your scripts, you may encounter a few different exceptions. Therefore, every time you create a script, you strive to provide the highest quality of code so if a first problem occurs, it creates and throws an exception and finally handle it.

Exception Hierarchy

Exceptional circumstances should be caught by the user application using this class. Another branch, such as error, is used by the other Java runtime systems to indicate the errors that are associated with it. Basically, under exceptions, there are two types of exceptions: one is checked and the other is unchecked. Let’s see the difference between these two exceptions: checked and unchecked exceptions.

A checked exception means it is an exception that is. The unchecked exception occurs during execution even though the compiler verified it during compilation. The checked exceptions are essentially referred to as compile-time exceptions while the unchecked exceptions are called runtime exceptions. To understand the checked exception, the programmer should handle this exception to maintain the normal flow of execution. Whereas the runtime exceptions can be ignored and there won’t be much difference in the flow of execution of the program. This is the main difference between the checked and unchecked exceptions.

class Exceptions

{

public static void main(String args[]) {

try {

}

catch (Exception e) {

}

 

This is how the structure of the exception looks. You create a class and write a try block inside the main method wherein you write a code that can raise an exception. Inside the catch block, you write the code that has to execute this. The code raises an exception that is included in the try block. So, the code throws an exception in the try block. Then, to continue with the normal execution flow, it is handled in the catch block.

Types of Exceptions in Selenium

There are different types of exceptions that are mentioned in the following:

WebDriverException

If you have the Chrome driver installed yet you attempt to conduct an activity, an error occurs when you attempt to do so. This exception is raised on a Mozilla Firefox driver which is a Geeko driver.

NoSuchElementException

This exception is thrown when the web driver does not find the element in the drum structure. That is, if you are not able to locate a particular element, it says no such element exception. That is, if that element is not present, that is the reason that it throws no such element exception.

try{

driver.get(“https://abc.com/iframe”);

driver.findElement(By.id(“timcd”)).sendKeys(….keysToSend:”Hello”);}

catch (NotFoundException e) {

system.out.printIn(“Not found”);

e.printStackTrace();

};

 

We saw a “Not found” exception in this code. First, you need to go to the URL. Then, switch to the frame and then type something. If you don’t switch and directly type into an element, it shows the “Not Found” error in the catch element.

NoSuchFrameException

If you want to perform an action that switches between the frames and you’re not able to do that because the child frame is not present or the parent frame is not able to navigate the child frame,  no such frame exception is raised in such cases.

NoAlertPresentException

This error appears when we attempt to perform a function that is either accepted or rejected and is not necessary at the location that is needed.

Similarly, we have a JavaScript alert. If we don’t click the JavaScript alert, there will be no alert in this case. If we try to switch that alert, it gives you a NoAlertPresentException.

TimeOutException

This exception is thrown when a command does not complete the task in a given amount of time.

Here are the methods to handle an exception with syntax:

TRY: It is used to specify a block where we place the exception code.

Try {

//code is written here

} catch (Exception_class_Name){}

 

CATCH: This block is used to handle the exception.

try {

catch(ExceptionName e1)

///catch block code}

 

THROW: This is used to throw an exception.

catch (Exception e) {

System.out.println(“Element is not Present.”);

throw(e);

 

THROWS: It is used to declare what the exception is.

public static void main(String[] args)

throws InterruptedException {}

 

FINALLY: It is used to execute the crucial code of the program.

try

{ ////critical code here}

catch (Exception e1)

[///catch block code}

finally {

////this block of code is must executed}

 

Methods to Handle an Exception with Codes

First, we create an exceptional class.

public class ExceptionhandlingExample

 

We first launch the Chrome driver to launch Google and navigate through a particular given website. Then, we use the thread dot sleep to sleep for 3000 which is three milliseconds. Then, we find an element by name which is “fake.click”. Now, this element is not present so what it does is throw an exception called “no such element” exception. Then, after running the code, we will see the Chrome driver launched.

WebDriver mydriver = new ChromeDriver();

mydriver.get(https://www.google.com);

Thread.sleeep(3000);

mydriver.findElement(By.name(“fake”)).click;

 

Nothing happened because the exception is raised here. As we can see, it throws an exception saying “no such element”.

Now, to handle it, we use the try and catch block. In the try block, use the following command:

}catch (NoSuchElementException e) {

System.out.println(“Element is not present.”);

System.out.println(“Hi”);

}

System.out.println(“Hi”);

 

We write the code that throws an exception. This code already throws an exception that no such element is found. In the try block, we write the “no such element” exception. Inside that, we print the “element is not found” and “hello”. Again, outside the try block, we want to check whether the normal flow of execution is carried or not. That is why we print this statement outside the block. After running the code, it doesn’t throw the exception. It prints “hello” two times: the first time is inside the catch block and the second time is outside the try and catch block. To ensure that the normal flow of the execution is not interrupted, this is how we can handle the exceptions:

In this example, we see the expected condition failure and how to handle it.

List<WebElementFacade> li;

@Override

public <T extends Actor> void performAs(T actor) {

li = BrowseTheWeb.as(actor).finadAll(By.xpath(//div[@class=’nav-fill’]//a[@data-csa-c-type=’link]));

for (int i=0;i<li.size();i++)

{

System.out.println(“--WebElementFacade List of Menu Name #### ” +li.get(i).getText());

}

 

After executing this code, we get the result where it prints all the values, but the test fails in the output window.

Now, we fix this error. If we loop more than one value before printing its value, we have to check whether the element are displayed or not or the value is displayed or not. Then, we can print that value. In that case, we write if  the “li. get.is” condition is displayed. This is to check the condition. Then, we write the print statement. After running the code, it reads all the values. As a result, we get the test passed. It reads all the values and as a result, we pass the test.

Conclusion

We understand the expected conditions in Selenium. We also discussed all checked and unchecked exceptions in the middle of the article. We discussed the types of exceptions with examples. Lastly, we covered how to handle the exceptions with codes. This article contains all the details on handling Selenium and the anticipated circumstances.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content