java.lang.NullPointerException in Selenium

            When the instance is null, with no variable or object is initialized, the error thrown by the web driver is null point exception.

For example, in selenium webdriver.

public static WebDriver driver;

            try {

            driver.get(“http://www.gmail.com”);

            System.setProperty(“webdriver.chrome.driver”,”c:\chromedriver.exe”);

            driver=new ChromeDriver();

            driver.findElement(By.xpath(“xpathemail”)).sendKeys(“username”);

            driver.findElement(By.xpath(“xpathpass”)).sendKeys(“password”);

            driver.quit();

             } catch (Exception e) {

           System.out.println(“The exception is” + e.printStackTrace());

}

From the code example, we can see that the driver is calling the geturl, before the driver is initialized with chrome browser driver, this is why we get the null pointer exception.

To fix this above exception.

            public static WebDriver driver;

            try {

            System.setProperty(“webdriver.chrome.driver”,”c:\chromedriver.exe”);

            driver=new ChromeDriver();

driver.get(“http://www.gmail.com”);

            driver.findElement(By.xpath(“xpathemail”)).sendKeys(“username”);

            driver.findElement(By.xpath(“xpathpass”)).sendKeys(“password”);

            driver.quit();

             } catch (Exception e) {

           System.out.println(“The exception is” + e.printStackTrace());

}

 The above code is modified and now you we can say there is no exception in the code, because, the driver is initialized first and used after the command

driver=new ChromeDriver();

Leave a Comment

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