# How to Create Custom Exceptions in anhtester/automationframeworkselenium

> Learn to create custom exceptions in anhtester/automationframeworkselenium by extending the base FrameworkException. Implement robust, standardized error handling for your automation.

- Repository: [Anh Tester/automationframeworkselenium](https://github.com/anhtester/automationframeworkselenium)
- Tags: how-to-guide
- Published: 2026-02-24

---

**The anhtester/automationframeworkselenium project provides a base `FrameworkException` class in the `com.anhtester.exceptions` package that you extend to create framework-specific runtime errors with standardized constructors and consistent error handling.**

Understanding how to create custom exceptions in anhtester/automationframeworkselenium allows you to replace generic Java exceptions with domain-specific error types for Selenium automation failures. The repository organizes all framework exceptions under a single package with a clear hierarchy, making it straightforward to add new exception classes that integrate with the existing reporting and logging infrastructure.

## Understanding the Exception Hierarchy

The project defines a small hierarchy of runtime exceptions located in `src/main/java/com/anhtester/exceptions/`. This structure distinguishes between framework-specific errors and general programming state errors:

- **`FrameworkException`** – The root unchecked exception extending `RuntimeException`. Located in [`FrameworkException.java`](https://github.com/anhtester/automationframeworkselenium/blob/main/FrameworkException.java), this class serves as the parent for all framework-wide errors that should abort test execution.

- **`InvalidPathForFilesException`** – Extends `FrameworkException` to signal problems with file system paths, such as missing or unreadable files.

- **`InvalidPathForExtentReportFileException`** – Extends `InvalidPathForFilesException` specifically for ExtentReport file configuration errors.

- **`InvalidRemoteWebDriverURLException`** – Extends `FrameworkException` to indicate invalid URLs for remote WebDriver Grid connections.

- **`TargetNotValidException`** – Extends `IllegalStateException` for invalid Selenium locator targets.

- **`HeadlessNotSupportedException`** – Extends `IllegalStateException` when headless mode is requested for an unsupported browser driver.

## Step-by-Step Guide to Create Custom Exceptions

### Choose the Proper Superclass

Select your parent class based on the error domain:

- **Extend `FrameworkException`** (or its subclasses) for automation-specific errors that should terminate the test run and appear in framework logs.
- **Extend `IllegalStateException`** (or other standard Java exceptions) for general programming logic errors unrelated to the automation framework.

### Create the Exception Class

Create a new Java file in `src/main/java/com/anhtester/exceptions/`. Name the class with the `Exception` suffix, declare it `public`, and include the `@SuppressWarnings("serial")` annotation to match the project's convention of omitting explicit `serialVersionUID` fields.

### Implement Standard Constructors

Every custom exception must provide at least two constructors:

1. `public YourException(String message)` – For simple error messages.
2. `public YourException(String message, Throwable cause)` – For exception chaining.

### Compile and Integrate

The Maven build automatically compiles new classes from `src/main/java`. No additional configuration is required after creating the file.

## Complete Example: CsvDataException

The following example demonstrates creating a custom exception for CSV data processing errors by extending `FrameworkException`.

First, define the exception class in [`src/main/java/com/anhtester/exceptions/CsvDataException.java`](https://github.com/anhtester/automationframeworkselenium/blob/main/src/main/java/com/anhtester/exceptions/CsvDataException.java):

```java
package com.anhtester.exceptions;

/**
 * Thrown when a CSV data file cannot be read or has an unexpected format.
 */
@SuppressWarnings("serial")
public class CsvDataException extends FrameworkException {

    public CsvDataException(String message) {
        super(message);
    }

    public CsvDataException(String message, Throwable cause) {
        super(message, cause);
    }
}

```

Next, implement the exception in a utility class:

```java
package com.anhtester.utils;

import com.anhtester.exceptions.CsvDataException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class CsvReader {
    public static String readFirstLine(String csvPath) {
        try {
            List<String> lines = Files.readAllLines(Paths.get(csvPath));
            if (lines.isEmpty()) {
                throw new CsvDataException("CSV file is empty: " + csvPath);
            }
            return lines.get(0);
        } catch (java.io.IOException e) {
            throw new CsvDataException("Failed to read CSV file: " + csvPath, e);
        }
    }
}

```

Finally, catch the specific exception in your test code:

```java
package com.anhtester.tests;

import com.anhtester.exceptions.CsvDataException;
import com.anhtester.utils.CsvReader;
import org.testng.annotations.Test;

public class DataDrivenTest {

    @Test
    public void testCsvReading() {
        try {
            String header = CsvReader.readFirstLine("src/test/resources/users.csv");
            // Perform assertions on header...
        } catch (CsvDataException e) {
            System.err.println("Data setup failed: " + e.getMessage());
            throw e; // Re-throw to fail the test with framework reporting
        }
    }
}

```

## Integration with Framework Reporting

The framework utilizes custom exceptions in utility classes such as [`ReportUtils.java`](https://github.com/anhtester/automationframeworkselenium/blob/main/ReportUtils.java), where `InvalidPathForExtentReportFileException` is thrown (lines 44–47) to signal configuration errors before the ExtentReport engine initializes. By throwing your custom exceptions during setup or test execution, you ensure that error messages appear consistently in both console logs and generated reports, providing clear context for debugging automation failures.

## Summary

- **Extend `FrameworkException`** for all automation-specific runtime errors to maintain consistency with the anhtester/automationframeworkselenium architecture.
- **Place new exceptions** in `src/main/java/com/anhtester/exceptions/` using the package `com.anhtester.exceptions`.
- **Implement dual constructors** accepting `(String message)` and `(String message, Throwable cause)` to support both simple errors and exception chaining.
- **Use `@SuppressWarnings("serial")`** to align with the project's approach to serialization warnings.
- **Throw domain-specific exceptions** to replace generic errors with meaningful messages that clarify the failure context for test maintainers.

## Frequently Asked Questions

### What is the base exception class in automationframeworkselenium?

The base class is `FrameworkException`, which extends `RuntimeException` and resides in [`src/main/java/com/anhtester/exceptions/FrameworkException.java`](https://github.com/anhtester/automationframeworkselenium/blob/main/src/main/java/com/anhtester/exceptions/FrameworkException.java). All framework-specific unchecked exceptions should inherit from this class to ensure consistent error handling across the test suite.

### Should I extend FrameworkException or IllegalStateException?

Extend `FrameworkException` for errors unique to your automation framework, such as invalid test data formats or missing configuration files. Extend `IllegalStateException` (or other standard JDK exceptions) for general programming logic errors that are not specific to the Selenium automation domain, such as invalid method call sequences.

### Where should I save new exception classes?

Save all custom exceptions in the `com.anhtester.exceptions` package, located at `src/main/java/com/anhtester/exceptions/`. This co-location with existing exceptions like `InvalidPathForFilesException` and `TargetNotValidException` ensures discoverability and adherence to the project's package structure.

### Does the project require serialVersionUID for custom exceptions?

No, the project consistently uses `@SuppressWarnings("serial")` instead of declaring explicit `serialVersionUID` fields. Follow this pattern in your custom exceptions to maintain uniformity with the existing codebase and avoid compiler warnings about missing serialization IDs.