Skip to main content

What is an Exception in Java

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

  1. Use Explicit Waits – Avoid Thread.sleep(), use WebDriverWait instead.
  2. Implement Try-Catch Blocks – Handle known exceptions properly.
  3. Use Page Object Model (POM) – Reduce stale element issues.
  4. Retry Mechanism – Handle flaky test scenarios.
  5. 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

Popular posts from this blog

Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript)

๐ŸŽฅ Setup Browser, Context, Page & Run Config Test Scripts with package.json & playwright.config.js Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript) 1. Install Playwright You can install Playwright using the following command: npm init playwright@latest 2. Create a Basic Test Script Understand the core Playwright architecture: Element Description browser Controls the browser instance (like Chrome, Firefox, etc.) context Acts like a separate browser profile (cookies, localStorage are isolated) page A single browser tab where interaction happens 3. Run the Test npx playwright test example.spec.js Ways to Run TypeScript Tests Way Command Notes ๐ŸŸข Via npx npx playwright test Uses built-in TypeScript support ๐ŸŸข With s...

Playwright Test Structure in Details -Session-02

๐ŸŽฅ Playwright: test.only, Hooks & Grouping with test.describe Explained Let’s go step-by-step , showing how to build from a single test , to using beforeEach / afterEach , and then organizing things with test.describe . ✅ Step 1: Basic Single Test with test.only import { test, expect } from '@playwright/test' ; test. only ( '๐Ÿš€ Basic test - check title' , async ({ page }) => { await page. goto ( 'https://example.com' ); await expect (page). toHaveTitle ( /Example Domain/ ); }); test.only ensures only this test runs — great for debugging. ✅ Step 2: Add beforeEach and afterEach import { test, expect } from '@playwright/test' ; test. beforeEach ( async ({ page }) => { console . log ( '๐Ÿ”„ Setting up before each test' ); await page. goto ( 'https://example.com' ); }); test. afterEach ( async ({ page }, testInfo) => { console . log ( `๐Ÿ“ฆ Finished test: ${testInfo.title} `); }); test. only ( ...

Playwright Locators in JavaScript (Complete Guide)

๐ŸŽฏ Playwright Locators in JavaScript (Complete Guide) This guide explains each Playwright locator with: ✅ What it is ๐Ÿ• When to use ⚙️ How to use it ๐ŸŽฏ Benefits ๐Ÿงช Code Examples ๐Ÿ”น 1. Locator by ID ✅ What: Selects an element with a unique id . ๐Ÿ• When: Element has a unique id . ⚙️ How: page.locator('#username') ๐ŸŽฏ Benefit: Fast and reliable. <input id="username" /> await page.locator('#username').fill('John'); ๐Ÿ”น 2. Locator by Class ✅ What: Selects by class . ๐Ÿ• When: Repeated or styled elements. ⚙️ How: page.locator('.password') ๐ŸŽฏ Benefit: Useful for shared styling. <input class="password" /> await page.locator('.password').fill('12345'); ๐Ÿ”น 3. Locator by Text ✅ What: Matches visible element text. ๐Ÿ• When: For buttons, links, etc. ⚙️ How: page.getByText('Login') ๐ŸŽฏ Benefit: Human-readable. <button>Login...