What is an Exception in Java?
An exception in Java is an event that disrupts the normal flow of the program during runtime. It occurs due to logical errors, incorrect user input, hardware failures, or resource unavailability. Java provides a robust mechanism to handle exceptions to ensure smooth execution.
How to Handle Exceptions in Java?
Java provides a structured way to handle exceptions using try-catch-finally blocks and the throws keyword.
1. Try-Catch Block
The try block contains the code that might throw an exception, and the catch block handles the exception.
try {
int num = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
2. Finally Block
The finally block always executes, whether an exception occurs or not.
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
3. Throws Keyword
The throws keyword is used to propagate exceptions.
public void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
System.out.println(a / b);
}
Types of Exceptions in Java
Java has two types of exceptions:
1. Checked Exceptions (Compile-Time)
These exceptions are checked at compile-time. The program will not compile unless they are handled.
| Exception | Description |
|---|---|
| IOException | When an input-output operation fails |
| SQLException | When a database query fails |
| FileNotFoundException | When the file is not found |
| ClassNotFoundException | When a class is not found |
Example of Checked Exception
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("test.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
2. Unchecked Exceptions (Runtime)
These exceptions occur at runtime and are not checked at compile-time.
| Exception | Description |
|---|---|
| NullPointerException | When an object reference is null |
| ArithmeticException | When an illegal arithmetic operation occurs |
| ArrayIndexOutOfBoundsException | When an array index is out of bounds |
| NumberFormatException | When a string is improperly converted to a number |
Example of Unchecked Exception
public class UncheckedExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // NullPointerException
}
}
Common Exceptions in Selenium Automation Testing
While using Selenium WebDriver, several exceptions may occur due to element absence, timing issues, stale elements, or browser-related problems.
1. NoSuchElementException
Occurs when an element cannot be found on the page.
Example
try {
WebElement element = driver.findElement(By.id("invalidID"));
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}
2. StaleElementReferenceException
Occurs when an element is no longer attached to the DOM.
Example
try {
WebElement element = driver.findElement(By.id("someID"));
driver.navigate().refresh();
element.click(); // Throws StaleElementReferenceException
} catch (StaleElementReferenceException e) {
System.out.println("Element is stale: " + e.getMessage());
}
3. TimeoutException
Occurs when a wait operation exceeds the specified time.
Example
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("delayedElement")));
} catch (TimeoutException e) {
System.out.println("Element loading timed out: " + e.getMessage());
}
4. ElementClickInterceptedException
Occurs when an element is not clickable due to another overlapping element.
Example
try {
WebElement button = driver.findElement(By.id("submitBtn"));
button.click();
} catch (ElementClickInterceptedException e) {
System.out.println("Element not clickable: " + e.getMessage());
}
5. WebDriverException
Occurs when WebDriver crashes or is unable to perform an operation.
Example
try {
driver.get("invalid_url"); // This will throw WebDriverException
} catch (WebDriverException e) {
System.out.println("WebDriver issue: " + e.getMessage());
}
6. JavascriptException
Occurs when JavaScript execution fails.
Example
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("invalidScript();");
} catch (JavascriptException e) {
System.out.println("JavaScript error: " + e.getMessage());
}
7. SessionNotFoundException
Occurs when a session is deleted or the browser is closed before an operation.
Example
try {
driver.quit();
driver.findElement(By.id("element")).click(); // Throws SessionNotFoundException
} catch (SessionNotFoundException e) {
System.out.println("Session is closed: " + e.getMessage());
}
Best Practices for Handling Selenium Exceptions
- Use Explicit Waits – Avoid
Thread.sleep(), useWebDriverWaitinstead. - Implement Try-Catch Blocks – Handle known exceptions properly.
- Use Page Object Model (POM) – Reduce stale element issues.
- Retry Mechanism – Handle flaky test scenarios.
- Log Errors Properly – Use logging frameworks like Log4j.
Conclusion
- Exceptions in Java help manage runtime errors.
- Handled using try-catch, finally, and throws.
- Selenium exceptions occur due to element unavailability, timing, or WebDriver issues.
- Proper exception handling ensures stable Selenium tests.
Would you like an example project that demonstrates these exceptions in a Selenium test case? ๐
Comments
Post a Comment