Skip to content

Iptv Assist

Learn More from us

Menu
  • HOW TO
  • Firestick
  • Chromecast
  • PC Apps
  • Lg Smart TV
  • IPTV Services
  • Automation Testing
  • Smart TV
  • Software Testing Tools
  • Contact Us
Menu

Top 10 Selenium Exceptions and How To Handle These (Exact Code)

Posted on January 29, 2023

Best Iptv Service Provider 2023 With 40k+ Channels And 100k+ VOD . 24/7 Suppport . Paypal Supported

Handling Selenium WebDriver Exceptions Using Exception Handling Framework – Selenium Tutorial #19

Best Iptv Service Provider 2023 With 40k+ Channels And 150k+ VOD . Hurry Up

Getting an exception in automation code is very common. ‘Exception’ as the word indicates, is a special or uncommon case.

Recommended IPTV Service Providers

  1. IPTVGREAT – Rating 4.8/5 ( 600+ Reviews )
  2. IPTVRESALE – Rating 5/5 ( 200+ Reviews )
  3. IPTVGANG – Rating 4.7/5 ( 1200+ Reviews )
  4. IPTVUNLOCK – Rating 5/5 ( 65 Reviews )
  5. IPTVFOLLOW -Rating 5/5 ( 48 Reviews )
  6. IPTVTOPS – Rating 5/5 ( 43 Reviews )

 

Automation code execution usually may not carry out as expected due to many factors involved in execution such as network stability issues, Internet issues, server stability etc. We might get exceptions due to insufficient waiting time or incorrect syntaxes, parameters etc.

Exception handling in Selenium 2

In the last WebDriver tutorial, we learned about 3 different types of important web elements like Web Tables, Frames and Dynamic elements and their handling mechanisms in selenium script

Before moving ahead with Framework tutorials in this Selenium training series, here in this tutorial we will learn about types of exceptions and how to handle exceptions in Java and Selenium scripts. Developers/testers use exception handling framework to handle an exception in selenium scripts.

What You Will Learn:

  • What is an Exception?
  • Advantages and Disadvantages of Avoid-Handle approach
  • Types of Exceptions in Java and Selenium
  • Exception Handling
  • Common Exceptions in Selenium WebDriver
  • Avoiding And Handling Common Exceptions
    • #1) org.openqa.selenium.NoSuchElementException
    • #2) org.openqa.selenium.NoSuchWindowException
    • #3) org.openqa.selenium.NoSuchFrameException
    • #4) org.openqa.selenium.NoAlertPresentException
    • #5) org.openqa.selenium.InvalidSelectorException
    • #6) org.openqa.selenium.ElementNotVisibleException
    • #7) org.openqa.selenium.ElementNotSelectableException
    • #8) org.openqa.selenium.TimeoutException
    • #9) org.openqa.selenium.NoSuchSessionException
    • #10) org.openqa.selenium.StaleElementReferenceException
  • Conclusion

What is an Exception?

Exceptions are events due to which java program ends abruptly without giving expected output. Java provides a framework where a user can handle exceptions.

The process of handling Exceptions is called Exception Handling.

Exceptions need to be handled because they break the normal flow of execution of a program. One of the important intentions of exception handling is to prevent this break and continue program execution. Sometimes, you might want to perform some series of actions on occurring of a certain exception.

When an exception occurs, an exception object is created which is technically referred to as ‘Throwing an Exception’ and we add Try/Catch blocks like,

try {
// Protected code 
} catch (ExceptionName e) {
// Catch block 
}

#1) The piece of code which might throw an exception is added inside the Try block.

#2) The Catch statement catches the exception and takes it as a parameter.

#3) When no exception is thrown, the try statement is executed and not the catch statement.

Example: When selenium script fails due to the wrong locator, then the developer should be able to understand the reason for failure and this can be achieved easily if the exception is handled properly in the program.

In my experience, it is best to try to avoid WebDriver exceptions whenever possible and catch truly exceptional cases. Use try/catch to handle things that go wrong and are outside my control.

Avoid the ones I can Catch others!

This is the best strategy that has worked for me.

For example, consider a test page that takes more than usual time to load on a test server. We will get frequent exceptions while doing actions on this page. So, instead of just catching this every time, we can

  • Add a wait command and try to avoid an exception
  • Use ‘Try/Catch’ to handle in case if a truly exceptional case has occurred

Thereby reducing the chances for exceptions.

Exceptions in selenium webdriver

Advantages and Disadvantages of Avoid-Handle approach

Advantages

Disadvantages

1) This approach reduces the chances of getting exceptions. 1) Increases the lines of codes because you add extra code to avoid exceptions
If an exception is still caught it 2) would be a truly exceptional case which is worth checking 2) Should have a better understanding of Web Driver API, commands and exceptions
Reduce debugging time. Automation code is intended to find bugs and you don’t want to see too many unwanted 3) exceptions and find the reasons behind each of them
4) In the Catch block, you deal with more valid cases
5) Reduce false failures
6) Clearer report

In this tutorial, we will discuss Avoid-And-Handle approach for the 10 most common exceptions in Selenium WebDriver. Before that, let’s get a basic understanding of Exception Handling and Try/Catch blocks.

Types of Exceptions in Java and Selenium

Below we have described the types of exceptions and the different ways how we can use exception handling framework in selenium scripts.

There are three kinds of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

The class hierarchy of exception and error:

Exception handling in Selenium

#1) Checked Exception: Checked exception is handled during compile time and it gives the compilation error if it is not caught and handled during compile time.

Example: FileNotFoundException, IOException etc.

#2) Unchecked Exception: In case of the unchecked exception, a compiler does not mandate to handle. The compiler ignores during compile time.

Example: ArrayIndexoutOfBoundException

#3) Error: When a scenario is fatal and the program cannot recover then JVM throws an error. Errors cannot be handled by the try-catch block. Even if the user tries to handle the error by using Try catch block, it cannot recover from the error.

Example: Assertion error, OutOfMemoryError etc.

Exception Handling

Try and Catch block:

try-catch blocks are generally used to handle exceptions. Type of exceptions is declared in catch block which is expected to come. When an exception comes in try block, immediately control moves to catch block.

Example:

try {
    br = new BufferedReader(new FileReader("Data"));
    } catch(IOException ie)
    {
         ie.printStackTrace();
    }

There can be multiple catch blocks for one try block depending upon the type of exception.

Example:

try {
    br = new BufferedReader(new FileReader("Data"));
    } catch(IOException ie)
    {
      ie.printStackTrace();
    } catch(FileNotFoundException file){
      file.printStackTrace();
    }

throws Exception:

throws keyword in java is used to throw an exception rather than handling it. All checked exceptions can be thrown by methods.

Example:

public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("Data"));
     while ((line = br.readLine()) != null)
         {
           System.out.println(line);
         }
}

finally block:

finally, block executes irrespective of execution of try-catch block and it executes immediately after try/catch block completes.

Basically file close, database connection etc. can be closed in finally block.

Example:

try {
    br = new BufferedReader(new FileReader("Data"));
    } catch(IOException ie)
    {
      ie.printStackTrace();
    }
Finally {
          br.close();
        }

In the above example, BufferReader stream is closed in finally block. br.close() will always execute irrespective of execution of try and catch block.

Note: finally block can exist without any catch block. It is not necessary to have a catch block always.

There can be many catch blocks but only one finally block can be used.

Throwable: Throwable is a parent class for error and exception. Generally, it is difficult to handle errors in java. If a programmer is not sure about the type of error and exception, then it is advised to use the Throwable class which can catch both error and exception.

Example:

try {
   br = new BufferedReader(new FileReader("Data"));
     } catch (Throwable t)
     {
       t.printStackTrace();
     }

Common Exceptions in Selenium WebDriver

Selenium has its own set of exceptions. While developing selenium scripts, a programmer has to handle or throw those exceptions.

Below are a few examples of exceptions in selenium:

All runtime exception classes in Selenium WebDriver come under the superclass WebDriverException.

Webdriver exceptions

Though there are many Exception classes under WebDriverException, we commonly see the below ones.

  • NoSuchElementException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException
  • InvalidSelectorException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • TimeoutException
  • NoSuchSessionException
  • StaleElementReferenceException

Details:

ElementNotVisibleException: If selenium tries to find an element but the element is not visible within the page

NoAlertPresentException: If a user tries to handle an alert box but the alert is not present.

NoSuchAttributeException: While trying to get attribute value but the attribute is not available in DOM.

NoSuchElementException: This exception is due to accessing an element which is not available on the page.

WebDriverException: Exception comes when a code is unable to initialize WebDriver.

Avoiding And Handling Common Exceptions

Let’s discuss Avoid-And-Handle approach for the above-mentioned exceptions:

#1) org.openqa.selenium.NoSuchElementException

This commonly seen exception class is a subclass of NotFoundException class. The exception occurs when WebDriver is unable to find and locate elements.

Usually, this happens when tester writes incorrect element locator in the findElement(By, by) method.

Consider that in the below example, correct id for the text field was ‘firstfield’ but the tester incorrectly mentioned it as ‘fistfield’. In this case, WebDriver cannot locate the element and org.openqa.selenium.NoSuchElementException will be thrown

driver.findElement(By.id("submit")).click();
Exception Handling:

try {
driver.findElement(By.id("submit")).click();
} catch (NoSuchElementException e)

In this case, the exception is thrown even if the element is not loaded.

Avoiding-And-Handling: Try giving a wait command.

Example: The wait command below waits 10 seconds for the presence of web element with id ‘submit’. Then it tries to click it. If the element is available but still the click fails, an exception is caught.

Using delayed time is a common practice in test automation to create a pause in between the steps. By adding a Try/Catch we ensure that the program continues even if the wait couldn’t help.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.presenceOfElementLocated(By.id("submit")));
try {
driver.findElement(By.id("submit")).click();
} catch (WebDriverException e) {
System.out.println(“An exceptional case.”);
}
} catch (TimeOutException e) {
System.out.println(“WebDriver couldn’t locate the element”);
}

#2) org.openqa.selenium.NoSuchWindowException

NoSuchWindowException comes under NotFoundException class. This is thrown when WebDriver tries to switch to an invalid window.

The below code can throw org.openqa.selenium.NoSuchWindowException if the window handle doesn’t exist or is not available to switch.

driver.switchTo().window(handle_1);

Avoiding-And-Handling: We would use window handles to get the set of active windows and then perform actions on the same.

In the example below, for each window handle, driver switch to is executed. Therefore chances of passing a wrong window parameter reduced.

for (String handle : driver.getWindowHandles()) {
try {
driver.switchTo().window(handle);
} catch (NoSuchWindowException e) {
System.out.println(“An exceptional case”);
}
}

#3) org.openqa.selenium.NoSuchFrameException

When WebDriver is trying to switch to an invalid frame, NoSuchFrameException under NotFoundException class is thrown.

The below code can throw org.openqa.selenium.NoSuchFrameException if a frame “frame_11” doesn’t exist or is not available.

driver.switchTo().frame(“frame_11”);

Exception Handling:

try {
driver.switchTo().frame("frame_11");
} catch (NoSuchFrameException e)

In this case, the exception is thrown even if the frame is not loaded.

Avoiding-And-Handling: Try to give a wait command.

In the example below, WebDriver waits for 10 seconds for the frame to be available. If the frame is available and still there is an exception, then it is caught.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.frameToBeAvaliableAndSwitchToIt(frame_11));
try {
driver.switchTo().frame("frame_11");
} catch (WebDriverException e) {
System.out.println(“An exceptional case”);
}
} catch (TimeOutException e) {
System.out.println(“WebDriver couldn’t locate the frame”);
}

#4) org.openqa.selenium.NoAlertPresentException

NoAlertPresentException under NotFoundException is thrown when WebDriver tries to switch to an alert, which is not available.

org.openqa.selenium.NoAlertPresentException will be thrown If below automation code calls accept() operation on Alert() class when an alert is not yet on the screen.

driver.switchTo().alert().accept();

Exception Handling:

try {
driver.switchTo().alert().accept();
} catch (NoSuchAlertException e)

In this case, the exception is thrown even if the alert is not loaded completely.

Avoiding-And-Handling: Always use explicit or fluent wait for a particular time in all cases where an alert is expected. If the alert is available and still there is an exception, then it is caught.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.alertIsPresent());
try {
driver.switchTo().alert().accept();
} catch (NoAlertPresentException e) {
System.out.println(“An exceptional case”);
}
} catch (TimeOutException e)
System.out.println(“WebDriver couldn’t locate the Alert”);
}

#5) org.openqa.selenium.InvalidSelectorException

This subclass of NoSuchElementException class occurs when a selector is incorrect or syntactically invalid. This exception occurs commonly when XPATH locator is used.

Consider the below example:

clickXPathButtonAndWait(“//button[@type=’button’][100]”);

This would throw an InvalidSelectorExeption because the XPATH syntax is incorrect.

Avoiding and Handling: To avoid this, we should check the locator used because the locator is likely incorrect or the syntax is wrong. Using Firebug to find xpath can reduce this exception.

Below code shows how to handle it using Try/Catch

try {
clickXPathButtonAndWait("//button[@type='button']");
} catch (InvalidSelectorException e) {
}

#6) org.openqa.selenium.ElementNotVisibleException

ElementNotVisibleException class is a subclass of ElementNotInteractableException class. This exception is thrown when WebDriver tries to perform an action on an invisible web element, which cannot be interacted with. That is, the web element is in a hidden state.

For example, in the below code, if the type of button with id ‘submit’ is ‘hidden’ in HTML, org.openqa.selenium.ElementNotVisibleException will be thrown.

driver.findElement(By.id("submit")).click();
Exception Handling:
try {
driver.findElement(By.id("submit")).click();
} catch (ElementNotVisibleException e)

In this case, the exception is thrown even if the page has not loaded completely.

Avoiding-And-Handling: There are two ways to do this. We can either use wait for the element to get completely.

The below code waits 10 seconds for the element. If the element is visible and still exception is thrown, it is caught.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.visibilityOfElementLocated(By.id(”submit”));
try {
driver.findElement(By.id("submit")).click();
} catch (WebDriverException e) {
System.out.println(“Exceptional case”);
}
} catch (TimeOutException e)
System.out.println(“WebDriver couldn’t find this element visible”);
}

#7) org.openqa.selenium.ElementNotSelectableException

This exception comes under InvalidElementStateException class. ElementNotSelectableException indicates that the web element is present in the web page but cannot be selected.

For example, the below code can throw a ElementNotSelectableException if the id “swift” is disabled.

Select dropdown = new Select(driver.findElement(By.id(“swift”)));

Exception Handling:

try {
Select dropdown = new Select(driver.findElement(By.id(“swift”)));
} catch (ElementNotSelectableException e)

In this case, exception is thrown even if the element becomes enabled after a while.

Avoiding-And-Handling: We can add a wait command to wait until the element becomes clickable. If there is still an exception, it is caught.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions. elementToBeClickable(By.id(”swift”));
try {
Select dropdown = new Select(driver.findElement(By.id("swift")));
} catch (WebDriverException e) {
System.out.println(“Exceptional case”);
}
} catch (TimeOutException e)
System.out.println(“WebDriver found that this element was not selectable.”);
}

#8) org.openqa.selenium.TimeoutException

This exception occurs when a command completion takes more than the wait time. Waits are mainly used in WebDriver to avoid the exception ElementNotVisibleException.

Sometimes test page might not load completely before next command in the program. If WebDriver tries to find an element in the webpage before the page completely loads, then exception ElementNotVisibleException is thrown. To avoid this exception, waits commands are added.

However, if the components don’t load even after the wait, the exception org.openqa.selenium.TimeoutException will be thrown.

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

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

In the above program, an implicit wait of 10 seconds is added. If the page www.softwaretestinghelp.com doesn’t load in 10 seconds, then TimeoutException will be thrown.

Avoiding and Handling: To avoid this, we can manually check the average time for a page to load and adjust the wait

Or, we can add explicit wait using JavaScript executor until the page is loaded.

In the below example, JavaScript executor is used. After page navigation, we call JavaScript return document.readyState for 20 seconds until “complete” is returned.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

wait.until(webDriver -> ((JavascriptExecutor)webDriver).executeScript("return document.readyState").equals("complete"));

driver.get("https://iptvassist.com");

#9) org.openqa.selenium.NoSuchSessionException

This exception is thrown when a method is called after quitting the browser by WebDriver.quit(). This can also happen due to web browser issues like crashes and WebDriver cannot execute any command using the driver instance.

To see this exception, the code below can be executed.

driver.quit()

Select dropdown = new Select(driver.findElement(By.id(“swift”)));

Avoiding and Handling: Always choose the latest stable version of browser to run Selenium Webdriver testcases.

This exception can be reduced by using driver.quit() at the completion of all tests. Do not try to use them after each test case. This can lead to issues when driver instance is null and upcoming test cases try to use it without initializing.

The below code creates WebDriver instance in the @BeforeSuite TestiNG annotation and destroys it in @AfterSuite TestiNG annotation

@BeforeSuite
public void setUp() throws MalformedURLException {
WebDriver driver = new FirefoxDriver();
}
@AfterSuite
public void testDown() {
driver.quit();
}

#10) org.openqa.selenium.StaleElementReferenceException

This exception says that a web element is no longer present in the web page.

This error is not the same as ElementNotVisibleException.

StaleElementReferenceException is thrown when an object for a particular web element was created in the program without any problem and however; this element is no longer present in the window. This can happen if there was a

  • Navigation to another page
  • DOM has refreshed
  • A frame or window switch

WebElement firstName = driver.findElement(By.id(“firstname”));

driver.switchTo().window(Child_Window);

element.sendKeys(“Aaron”);

In the code above, object firstName was created and then the window was switched. Then, WebDriver tries to type ‘Aaron’ in the form field. In this case StaleElementReferenceException is thrown.

Avoiding and Handling: Confirm that we are trying to do the action in the correct window. To avoid issues due to DOM refresh, we can use Dynamic Xpath

Let’s discuss another example.

Say ‘id’ of a username field is ‘username_1’ and the XPath will be //*[@id=’firstname_1?]. When you open the page again the ‘id’ might change say to ‘’firstname _11’. In this case, the test will fail because the WebDriver could not find the element. In this case, StaleElementReferenceException will be thrown.

In this case, we can use a dynamic xpath like,

try {
driver.findElement(By.xpath(“//*[contains(@id,firstname’)]”)).sendKeys(“Aaron”);
} catch (StaleElementReferenceException e)

In the example above dynamic XPATH is used and if the exception is still found, it is caught.

Conclusion

Exception handling is the essential part of every java program as well as selenium script. We can build robust and optimal code by handling an exception in smart ways. And it is also a best practice to handle exceptions in a script which will give you a better report when a program fails due to any reason.

Here we have tried to cover the process and framework of exception handling which is required to be implemented in selenium scripts.

Remember it is not mandatory to always handle the exception in a try-catch block. You can also throw an exception depending upon the requirement in a script.

An exception shouldn’t be ignored as they break program execution. In this tutorial, we went through different exceptions and ways to reduce the chances of getting them through manual checks and codes.

Adding waits can control some cases like ‘NoSuchElementException‘, ‘ElementNotFoundException‘, ‘ElementNotVisibleException‘.

Next Tutorial #20: In the upcoming tutorial, we would discuss the various types of testing frameworks available. We would also study the pros and cons of using a fledged framework approach in automation testing. We would discuss in detail about the Test data-driven framework.

Please post your queries, related to handling exception in Selenium WebDriver, if you have any.

Related

Best Iptv Service Provider 2023 With 40k+ Channels And 150k+ VOD . Hurry Up

Leave a Reply Cancel reply

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

Recent Posts

  • IPTV List: Best iptv lista 2023
  • IPTV Premium: Best Premium IPTV Service Provider List And Benefits
  • Nikon IPTV Review: Over 10,000 Live Channels for $12/Month
  • Iptvwings. Com Review: +18000 Live IPTV Channels ,+70000 Movies, +40000 TV show For $15/1 month
  • IPTVUNO Review: More Than 16000 Live TV channels, 55,000 Movies & VOD For $15/Month

Recent Comments

  1. IPTV List: Play lista iptv 2022 - Iptv Assist on Best IPTV Player in 2023 for Watching Live TV
  2. Cola IPTV – Over 18,000 Live Channels for $12/Month - Iptv Assist on FileLinked – How to Install on Firestick/Fire TV and Android Devices
  3. Cola IPTV – Over 18,000 Live Channels for $12/Month - Iptv Assist on 50+ Best IPTV Service Providers for Streaming Live TV 2023
  4. XoomsTV IPTV – Over 11,000 Channels & VOD for Under $13/Month on Best VPN for IPTV in 2023 and How to Install on Firestick/Android
  5. Voodoo Streams IPTV Review – Over 12,000 Channels for $11/Month - Iptv Assist on Dynasty TV IPTV Review – Over 6,000 Channels for $10/Month

Archives

  • January 2023

Categories

  • Activate
  • Agile Testing
  • Alternatives
  • Android
  • APK
  • Apple TV
  • Automation Testing
  • Basics of Software Testing
  • Best Apps
  • Breakfast Hours
  • Bug Defect tracking
  • Career in Software Testing
  • Chromebook
  • Chromecast
  • Cross Platform
  • Database Testing
  • Delete Account
  • Discord
  • Error Code
  • Firestick
  • Gaming
  • General
  • Google TV
  • Hisense Smart TV
  • HOW TO
  • Interview Questions
  • iPhone
  • IPTV
  • IPTV Apps
  • Iptv Service SP
  • IPTV Services
  • JVC Smart TV
  • Kodi
  • Lg Smart TV
  • Manual Testing
  • MI TV
  • Mobile Testing
  • Mod APK
  • newestiptv.com
  • News
  • Nintendo Switch
  • Panasonic Smart TV
  • PC Apps
  • Performance Testing
  • Philips Smart TV
  • PS4
  • PS5
  • Python
  • QA Certifications
  • QA Leadership
  • QA Team Skills
  • Quality Assurance
  • Reddit
  • Reviews
  • Roku
  • Samsung Smart TV
  • Screenshot
  • Selenium Tutorials
  • Sharp Smart TV
  • Skyworth Smart TV
  • Smart TV
  • Soft Skills For Testers
  • Software Testing Templates
  • Software Testing Tools
  • Software Testing Training
  • Sony Smart TV
  • Sports
  • Streaming Apps
  • Streaming Devices
  • Tech News
  • Test Management Tools
  • Test Strategy
  • Testing Best Practices
  • Testing Concepts
  • Testing Methodologies
  • Testing News
  • Testing Skill Improvement
  • Testing Tips and Resources
  • Toshiba Smart TV
  • Tutorials
  • Twitch
  • Types of Testing
  • Uncategorized
  • Vizio Smart TV
  • VPN
  • Web Testing
  • What is
  • Xbox
©2023 Iptv Assist | Design: Newspaperly WordPress Theme