- Powerful techniques to handle exception in Selenium with Java
- Advantage to handle exception in Selenium
- What are the techniques to handle an exception in Selenium using Java programming language?
- Recommended Tutorials:
- Use of “Try – Catch” block to handle exception in Selenium
- Use of “Try – Multiple Catch” blocks to handle exception in Selenium
- Use of “Nested Try –Catch” blocks to handle exception in Selenium
- Use of “finally” block to handle exception in Selenium
- Use of “throw” keyword to handle exception in Selenium
- Use of “throws” keyword to handle exception in Selenium
- Related Posts
- WebDriver Event Listener for effective Logging and Reporting
- Handle hidden elements with Selenium WebDriver
- How to execute test in Headless browser with Selenium WebDriver?
- Checkpoints, Breakpoints & Startpoints in Selenium WebDriver
- About The Author
- How to use Exception Handling in Selenium Webdriver?
- How to Handle Exception in Selenium Webdriver
- Handle exception in Selenium
- Reader Interactions
- Comments
Powerful techniques to handle exception in Selenium with Java
Many people utter how to handle the exception in Selenium! But one thing I would like to clear very straightforward that Selenium itself never handles Exception, Rather, It is the programming language which you use that gives you an environment to handle the exception in Selenium. Hope you got the point. Therefore, you must be good in the programming language which you have chosen to work with Selenium. In this tutorial, I am going to tell you exception handling in Selenium by using Java programming. Whatever, I will discuss here that will be the base to whichever programming language you will use for your Automation testing project with Selenium.
Before we proceed to our tutorial on exception handling, I’d highly recommend you to know the 20 types of major exceptions in Selenium. Once you go through these exceptions then you will be pretty clear about the scenarios where tests are likely to fail because of Exceptions. One thing, you should always keep in your mind that Selenium is nothing to do with Exception; however, it is the programming language which you are using will only deal with the exceptions. So, be prepared with your programming language, like Java.
Now I assume that you have gone thoroughly with the chapter on different types of Exceptions in Selenium, so today we will take forward the topic and will skip the already discussed one.
Hence, let’s begin with the advantage of handling the exception in Selenium.
Advantage to handle exception in Selenium
In general, a program will fail to continue its execution when the user gives input to divide any number by zero. Because in real time such arithmetic operation is not feasible, hence, Java will throw an Arithmetic Exception at runtime, thus, the program likely to terminate. Just to avoid the abnormal termination of the program we use exception handling. Hence, this is the major advantage of using an exception handler.
Suppose there are 100 statements and the normal flow of the execution gets terminated after 50 th statement due to some abnormal behavior which we didn’t consider while writing the code. So in this case program stops its execution at the middle point. Now think, if we inject exception handler at the 50 th position then Java will send the log of exception to console and further execution of the program will be continued normally.
What are the techniques to handle an exception in Selenium using Java programming language?
We mainly extend the core techniques cum methods of base programming language to handle exceptions in Automation testing. So here are the techniques listed below which we use to handle the exception in Selenium using Java programming:
- Try – Catch
- Try with multiple catches
- Nested try – catch
- Finally block
- Throw keyword
- Throws Keyword
Recommended Tutorials:
Let’s start with Try – Catch first.
Use of “Try – Catch” block to handle exception in Selenium
Till now we have ideas about the types of exception that may come during Selenium test automation exception. So once we have figured out the kind of exception which probably may come then we pass the object of that exception as an argument within catch statement. Moreover, the main business test logic will within try statement. Here is the example:
Now the question you may ask, what happens if we don’t handle the exception?
The immediate cause is program will be terminated at that moment itself, which we have discussed many times. Therefore, let me tell you the working procedure of JVM if we do not handle the exception. In addition to program termination, JVM prints out stake trace as well as exception description in the console.
Use of “Try – Multiple Catch” blocks to handle exception in Selenium
Here you will learn the sequence in which exceptions are handled. This technique will be applicable where there are chances of getting different kinds of exception while your program starts the execution. A set of rules are defined when you use multiple catch block with a single try statement. Those rules are as follows:
Rule#1: At a time, only one exception will occur so the only one catch statement will come into action.
Rule#2: You must follow the order to pass the object of the exception as an argument in the catch statement. Thus, you must give most specific exception to the most general one. For example, NoSuchElementException to Exception.
try < //Business test logic goes here, that may cause exception >catch (NoSuchWindowException e) < System.out.println(“Specific Exception1- ”+e); >catch (NoSuchElementException e1) < System.out.println(“Specific Exception2- ”+e); >catch (Exception e2)
Use of “Nested Try –Catch” blocks to handle exception in Selenium
It is same as Nested If – Else Statement. In this case, a part of try statement will have one set of business test logic, whereas, another set of try statement will have some modular business test logic. Likewise, we handle multiple exceptions by using nested try-catch blocks in Selenium using Java.
try < try< //Business test logic goes here, that may cause exception >catch (Exception e) < System.out.println(“Exception- ”+e); >try < //Business test logic goes here, that may cause exception >catch (Exception e1) < System.out.println(“Exception- ”+e1); >> catch (Exception e_super)
Use of “finally” block to handle exception in Selenium
If you are using finally block then it doesn’t matter whether your program handles exception properly or not, but statement written within “finally” block will be always executed. This is the beauty of OOPS programming language.
So in which scenario, you can use finally block. Hence, you can use finally block where there is a requirement of closing connection, closing files, cleaning up of the session and so on.
One thing you should keep in your mind, you include catch block in your program or not, but when you include finally block then the entire exception handler will be valid, even without catch statement.
try < //Business test logic goes here, that may cause exception >catch (Exception e1) < System.out.println(“Exception- ”+e1); >finally
Use of “throw” keyword to handle exception in Selenium
When you have programmed any custom exception then you can use throw keyword. It explicitly throws the exception and it includes both checked and unchecked exception in it.
throw new ExceptionType(“Your message here”);
Use of “throws” keyword to handle exception in Selenium
This is highly useful to handle checked exception. A programmer can propagate the checked exception for the specific method.
public void yourMethodName() throws Exception1, Exception2, Exception3 < //Business test logic goes here >
Related Posts
WebDriver Event Listener for effective Logging and Reporting
Handle hidden elements with Selenium WebDriver
How to execute test in Headless browser with Selenium WebDriver?
Checkpoints, Breakpoints & Startpoints in Selenium WebDriver
About The Author
Avinash Mishra
Avinash Mishra is the author of Inviul blog. He is a software engineer and blogger by choice. He loves to write blogs, and apart from blogging, he is interested in documentary film making, listening to music, traveling around the world and philanthropic activities.
How to use Exception Handling in Selenium Webdriver?
The Scenario is as follows: When the code driver.get(url); runs, if the URL is not able to access (if server is not reachable) then it should throw an exception that server is not reachable and the code should stop executing the next line
driver.findElement(By.id("loginUsername")).sendKeys(username);
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class A < static Properties p= new Properties(); String url=p.getProperty("url"); private static Logger Log = Logger.getLogger(A.class.getName()); public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, InterruptedException < WebDriver driver = new FirefoxDriver(); A a = new A(); Actions actions = new Actions(driver); DOMConfigurator.configure("src/log4j.xml"); String url = a.readXML("logindetails","url"); String username = a.readXML("logindetails","username"); String password = a.readXML("logindetails","password"); //use username for webdriver specific actions Log.info("Sign in to the OneReports website"); driver.manage().window().maximize(); driver.get(url);// In this line after opens the browser it gets the URL from my **D://NewFile.xml* file and try to open in the browser. If the Server is not reachable then it should stop here. else it takes the username and password from the same file then it will open the page in browser. Thread.sleep(5000); Log.info("Enter Username"); driver.findElement(By.id("loginUsername")).sendKeys(username); Log.info("Enter Password"); driver.findElement(By.id("loginPassword")).sendKeys(password); //submit Log.info("Submitting login details"); waitforElement(driver,120 , "//*[@id='submit']"); driver.findElement(By.id("submit")).submit(); Thread.sleep(5000); >private static void waitforElement(WebDriver driver, int i, String string) < // TODO Auto-generated method stub >public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException < String ele = null; File fXmlFile = new File("D://NewFile.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(searchelement); Node nNode = nList.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) < Element eElement = (Element) nNode; ele=eElement.getElementsByTagName(tag).item(0).getTextContent(); >return ele; > >
I tried this try block method as well. But it’s not catching the exception just moving to the driver.findElement(By.id(«loginUsername»)).sendKeys(username); Error in code
line and I’m getting error as follows in the console:Unable to locate element: Command duration or timeout: 262 milliseconds
How to Handle Exception in Selenium Webdriver
Hello Welcome to Selenium Tutorial, today we are going to discuss how to Handle Exception in Selenium Webdriver without using much code.
In Selenium, we are going to face so many exceptions some of them are listed here.
What is Exception?
An exception in Java in an event, which can disturb our program flow or you, can say it can terminate our program. An exception can come during execution of the program so we should follow better exception handling in our program/script.
What is Exception handling?
Exception handling is a concept in the programming language to save our program from terminating. Let me explain in with the help of simple example
If we execute our program then at run time definitely, it is going to throw an exception called ArthematicException
Like this, we have the multiple exceptions in Selenium as well so let us see how we can handle this.
Handle exception in Selenium
In Java , we can handle exception using try- catch block.
Syntax: 1- try with 1 catch
try < // Code which can throw exception >catch(ExceptionClass objectname) < // Take necessary actions when exception come >
Syntax 2- try with multiple catch block
try < // Code which can throw exception >catch(ExceptionClass1 objectname) < // Take necessary actions when exception come >catch(ExceptionClass2 objectname) < // actions >catch(ExceptionClass3 objectname) < // actions >
Note- Make sure Parent Exception should come in last catch block otherwise we will face code , not reachable error.
Scenario for Selenium-
Consider a scenario in which we have to find an element with the help of XPath, id ,name etc. and if Selenium is not able to find that element then it will throw NoSuchElementException and it will terminate your program, so in this we have to use try-catch block so that we can save our program being terminated.
try < driver.findElement(By.id("someid")).click(); >catch(NoSuchElementException e)
We have the same exception in java.util also so make sure you have to import following package
For better automation practice always, try to use Exception handling.
Hope you like above post. Please comment if you finding any issue.
Please share with others as well. Have a nice day 🙂
Reader Interactions
Comments
Hi Sanjay, if you handle with catch then it will mark as pass but in catch if you throw some exception then it will mark as fail.
is there any another solution to handle nosuch element exception?other than try catch block.if u run the testcase in authentic mode…
Hi Mukesh, At first i would like to appreciate your work and the efforts you put in.
I have some issue with gmail page. In detail, When an user enters invalid username in “Enter your email” field and click “next” button, the page will generate and error text. I am unable to find that element by element locator. I have tried with xpath, ID but got an NoSuchElementexception.
It would be helpful if you let me know hand to find element with standard Element locators. Thanks in advance,
Sandeep
Hi Sandeep, Kindly use contains method of xpath or Text() method of xpath. I always use this to capture error messages. Kindly refer http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/ and http://learn-automation.com/capture-error-message-in-selenium/
is there any another solution to handle NO such element exception?and I want to know how to send the reports generated through TestNG via mail once the execution is complete.Please help…….
woow
I faced many problems previously in my script and i did not solve because i dont know how to handle exception. After read your article it is now vwey clear and easy to me to solve exception error. Thanks.
Hi Mukesh,
I want to know how to send the reports generated through TestNG via mail once the execution is complete.Please help.
Hi Mukesh,
I want to know how to send the reports generated through TestNG via mail once the execution is complete.Please help.
Please share the same to me: how to send the reports generated through TestNG via mail once the execution is complete