Exception in java and selenium
A NullPointerException (NPE) occurs in Java when you try to use an object reference that points to null. It means the variable has been declared but not assigned any valid object before being used.
Common Causes of NullPointerException
- Uninitialized Object
WebDriver driver; // declared but not initialized
driver.get("https://example.com"); // NPE here
- Page Object Not Initialized
LoginPage lp;
lp.login("user", "pass"); // NPE because lp = null
- Array or Collection Not Initialized
int[] arr = null;
int n = arr.length; // NPE
- Return Value is Null
String text = getText(); // method returns null
System.out.println(text.length()); // NPE
- Chained Calls on Null Reference
String name = null;
int len = name.trim().length(); // NPE
How to Handle NullPointerException
1. Prevent It (Best Practice)
Always initialize variables before using them.
For Selenium:
WebDriver driver = new ChromeDriver();
- For Page Objects:
LoginPage lp = new LoginPage(driver);
2. Null Checks (Defensive Programming)
if (obj != null) {
obj.doSomething();
}
3. Use Optional (Java 8+)
Optional<String> name = Optional.ofNullable(getUserName());
name.ifPresent(n -> System.out.println(n.length()));
4. Default Values
String text = (getText() != null) ? getText() : "Default Text";
5. Proper Initialization in Frameworks
Use
@BeforeMethodor@BeforeClassin TestNG to initialize objects.Example:
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
loginPage = new LoginPage(driver);
}
6. Catching NPE (Last Resort – Not Recommended for Prevention)
try {
obj.doSomething();
} catch (NullPointerException e) {
System.out.println("Object was null!");
}
Note: Catching NPE is rarely recommended; it hides the real cause. Always fix the root cause.
How to Debug NullPointerException
Look at the stack trace – it shows the exact line.
Check which variable is null on that line.
Trace back where that variable was initialized.
Fix the missing initialization or add a proper check.
Example in Selenium (Cause & Fix)
Problem:
public class LoginTest {
WebDriver driver;
LoginPage lp;
@Test
public void testLogin() {
lp.login("admin", "admin123"); // NPE because lp is never initialized
}
}
Solution:
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.get("https://example.com");
lp = new LoginPage(driver); // FIX: Proper initialization
}