Common Selenium Exceptions and how to handle them – Selenium Tutorial # 19

Tram Ho

Catching an exception – exceptions in automation code are very common. ‘Exceptions’ denote special or uncommon circumstances.

Automatic code execution may not be as expected due to many objective factors involved in the execution such as network stability problems, Internet problems, server stability, etc. From there they are. You may get an exception returned due to insufficient timeouts or syntax, incorrect parameters, and so on.

Therefore, learning about exceptions and how to handle them is essential in the generation of automation codes.

What is Exception?

Exceptions are events caused by the program terminating suddenly without giving the expected result. Java provides a framework where users can handle exceptions.

The process of handling exceptions is called Exception Handling.

Exceptions need to be handled because they break the normal execution of a program. One of the important purposes of exception handling is to prevent this break in order to continue executing the program. Or take some action when an exception occurs.

When an exception occurs, an exception object ‘Throwing an Exception’ is initialized with Try / Catch blocks, for example:

  • When an exception e occurs, the catch statement will be executed.
  • When there is no exception e , the try statement is executed and statement catch ignored
  • Should use try / catch to handle things that are out of control and wrong.

Avoid-And-Handle methods should be used to avoid the exception first, if the exception cannot be avoided, then handle it.

Advantages and disadvantages of this Avoid-Handle method:

Advantages:

  • Reduces your chances of getting an exception
  • If an exception is still caught then it would be a really special case worth checking out
  • Reduced debugging time. The automation code is intended to find the error and you don’t want to see too many unwanted exceptions and find the reason behind each of them.
  • In Catch block, you deal with more valuable cases
  • Reduce errors
  • Report more clearly

Defect:

  • Increase the number of lines of code because you add additional code to avoid exceptions
  • Knowledge of Web Driver APIs, commands, and exceptions is required

To learn about this Avoid-And-Handle method, you first need to understand the basics of Exception Handling and Try / Catch blocks.

Exceptions in Java and Selenium

There are 3 types of exception:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

The exception and error class hierarchy:

# 1) Checked Exception: is handled at compile time and will cause a compiler error if it is not caught and handled at compile time (must be handled in order to continue compiling the program)

For example: FileNotFoundException, IOException …

# 2) Unchecked Exception: In this case the compiler doesn’t have to handle it. Compiler skips during compile time.

Example: ArrayIndexoutOfBoundException

# 3) Error: When a critical scenario occurs and the program cannot recover itself, the JVM will generate an error. The try-catch block cannot handle this error. Even if a user tries to handle the error using the try-catch block, it cannot recover from the error.

Examples: Assertion error, OutOfMemoryError ….

Exception Handling

Try and Catch block:

Try-catch blocks are often used to handle exceptions. The expected exception types are declared in the catch block (// IOException ie). When an exception appears in the try block, the controller will immediately navigate to the catch block ( //ie.printStackTrace ()):

It is possible to combine multiple exceptions in a try block:

throws Exception:

The throws keyword is used to throw / throw an exception instead of handling it. All exceptions are checked exception that can be thrown by methods. For example:

Finally block:

The block executes regardless of how the try-catch block is executed and is executed immediately after the try / catch block completes.

Closing files, disconnecting databases, etc .. can be done in this (final) block. For example:

In the above example, the BufferReader thread is closed on the Finally block. The br.close(); command br.close(); will always be executed regardless of how the try – catch block is executed.

Attention:

  • The Finally block is an independent block, which exists without having any catch block
  • There may be many catch blocks but there is only 1 Finally only block.

Throwable:

Throwable is the superclass of errors and exceptions. If you are unsure of the error and exception types then use the Throwable class for safety, which can catch both errors and exceptions. For example:

The common exceptions in Selenium WebDriver

Selenium has its own set of exceptions. While developing selenium scripts you need to handle or remove these exceptions.

Here are some examples of these exceptions:

All exception runtime classes in Selenium WebDriver fall under the superclass WebDriverException class:

There are many Exception classes in WebDriverException, common or see some of the following classes:

  • NoSuchElementException: This exception is caused by accessing an element that is not available on the page.
  • NoSuchElementException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException: The user tries to handle the warning box but the warning does not appear.
  • InvalidSelectorException
  • ElementNotVisibleException: Selenium tries to find an element, but it’s not visible on the page
  • ElementNotSelectableException
  • TimeoutException
  • NoSuchSessionException
  • StaleElementReferenceException
  • WebDriverException: An exception occurs when the code cannot initialize WebDriver.

Avoiding and Handling the common exceptions (outlined above)

# 1) org.openqa.selenium.NoSuchElementException

This common exception class is a subclass of the NotFoundException class. Exceptions occur when WebDriver cannot find and locate elements. This usually occurs when the tester writes the incorrect element locator in the findElement(By, by) .

Consider that in the example below, the correct id for the text field is “firstfield” but the examiner misspelled it as “fistfield”. In this case, the WebDriver cannot locate the element and org.openqa.selenium.NoSuchElementException will be fired:

Avoiding-And-Handling : Try issuing a pending order. For example:

The command will wait 10 seconds for the presence of the web element with id ‘submit’. Then the try command does click it. If the element is available but the click still fails, an exception will be caught.

Using delay is a common method in automated testing to create gaps between steps. By adding a Try / Catch block, it is possible to ensure that the program will continue even when the wait cannot help.

# 2) org.openqa.selenium.NoSuchWindowException

NoSuchWindowException is in the NotFoundException class. This exception is fired when WebDriver tries to switch to an invalid window.

The code below fires org.openqa.selenium.NoSuchWindowException if the window doesn’t exist or isn’t available for conversion.

Avoiding-And-Handling : Use window handles to get set of active windows and then perform similar actions.

In the example below, the driver switch is executed for each window handle. Hence, the risk of passing an incorrect window parameter is reduced.

# 3) org.openqa.selenium.NoSuchFrameException

When WebDriver tries to convert an invalid frame, NoSuchFrameException in the NotFoundException class is fired.

The example code below will fire org.openqa.selenium.NoSuchFrameException if frame_11 does not exist or is not available.

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

Exception Handling:

In this case, the exception is fired even when the frame is not loaded.

Avoiding-And-Handling : Try issuing a pending order. For example:

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

# 4) org.openqa.selenium.NoAlertPresentException

NoAlertPresentException located in NotFoundException is fired when WebDriver tries to switch to an unavailable warning.

org.openqa.selenium.NoAlertPresentException will be fired if the call accept() operates on the Alert class when an alert has not appeared on the screen.

Exception Handling:

In this case, the exception is thrown even when the warning is not completely loaded.

Avoiding-And-Handling: In any case where a warning is expected, always use an explicit wait or the fluent wait for a specific time. If the alert is available and there is an exception, it will be caught.

# 5) org.openqa.selenium.InvalidSelectorException

This is a subclass of NoSuchElementException , which occurs when a selector is incorrect or syntactically invalid. This exception usually occurs when using the XPATH locator. For example:

This will generate an invalid error because the XPATH syntax is incorrect.

Avoiding and Handling: To avoid this we should check the locator used since the locator may be inaccurate or syntactically incorrect. Using Firebug to find xpath alleviates this exception.

How to handle this exception uses Try / Catch

# 6) org.openqa.selenium.ElementNotVisibleException

The ElementNotVisibleException is a subclass of ElementNotInteractableException . This exception is fired when WebDriver tries to perform an action on a hidden web element, unable to interact with the element. That is, the web element is in the hidden state.

For example , in the code below, if the button id = ‘submit’ is ‘hidden’ in the HTML, org.openqa.selenium.ElementNotVisibleException will be fired.

In this case, the exception is fired even when the page has not been completely loaded.

Avoiding-And-Handling: We can use the pending command for the fully received element. The code below waits 10 seconds for the element to appear. If the element shows up and still throws the exception, it will be caught.

# 7) org.openqa.selenium.ElementNotSelectableException

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

For example, the following code will return an ElementNotSelectableException if id “swift” is disabled.

Exception Handling:

In this case, the exception is thrown even if the element is turned on after a while.

Avoiding-And-Handling: Adds an order to wait until the element is clickable. If there are exceptions, it will be caught.

# 8) org.openqa.selenium.TimeoutException

This exception occurs when an order completes taking longer than the time to wait. Wait commands are mainly used in WebDriver to avoid the exception ElementNotVisibleException : Sometimes the test page may not be completely loaded before the next command in the program. If WebDriver tries to find an element in the web page before the page loads completely, the ElementNotVisibleException is fired. To avoid this exception, pending orders are added.

However, if the components fail to load even after waiting, the org.openqa.selenium.TimeoutException will be thrown.

In the code above, a default timeout of 10 seconds is added. If the www.softwaretestinghelp.com page does not load within 10 seconds, a TimeoutException will be fired.

Avoiding and Handling: To avoid this, we can manually check the average page load time and adjust the latency. Or, you can add an explicit wait using the JavaScript runtime until the page loads.

In the example below, the JavaScript executable is used. After navigating the page, calling the JavaScript returns document.readyState for 20 seconds until “complete” is returned.

Epilogue

Exception handling is an essential part of every java program as well as selenium script. Thanks to handling exceptions in clever ways, we can build robust and optimized code. If you are interested, see the original article here:

https://www.softwaretestinghelp.com/exception-handling-framework-selenium-tutorial-19/

Share the news now

Source : Viblo