TheAlgorithms/Java · error · IllegalArgumentException

Number of vertices cannot be negative

Error message

Number of vertices cannot be negative

What it means

Thrown by the WelshPowell.Graph constructor when `vertices` is negative. The constructor allocates `HashSet[vertices]`, so a negative count is invalid. Zero is allowed (an empty coloring domain). Reached via `WelshPowell.makeGraph(numberOfVertices, edges)`.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java:46

    private WelshPowell() {
    }

    /**
     * Represents a graph using an adjacency list.
     */
    static final class Graph {
        private final HashSet<Integer>[] adjacencyLists;

        /**
         * Initializes a graph with a specified number of vertices.
         *
         * @param vertices the number of vertices in the graph
         * @throws IllegalArgumentException if the number of vertices is negative
         */
        private Graph(int vertices) {
            if (vertices < 0) {
                throw new IllegalArgumentException("Number of vertices cannot be negative");
            }

            adjacencyLists = new HashSet[vertices];
            Arrays.setAll(adjacencyLists, i -> new HashSet<>());
        }

        /**
         * Adds an edge between two vertices in the graph.
         *
         * @param nodeA one end of the edge
         * @param nodeB the other end of the edge
         * @throws IllegalArgumentException if the vertices are out of bounds or if a self-loop is attempted
         */
        private void addEdge(int nodeA, int nodeB) {
            validateVertex(nodeA);
            validateVertex(nodeB);
            if (nodeA == nodeB) {
                throw new IllegalArgumentException("Self-loops are not allowed");

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate `vertices >= 0` before building the graph
  2. Fix the upstream computation producing the negative value
  3. Reject the input early at the parse boundary

Example fix

// before
Graph g = WelshPowell.makeGraph(n - 1, edges);
// after
if (n < 0) throw new IllegalArgumentException("n >= 0");
Graph g = WelshPowell.makeGraph(n, edges);
Defensive patterns

Strategy: validation

Validate before calling

if (numberOfVertices < 0) {
    throw new IllegalArgumentException("vertices must be >= 0");
}

Try / catch

try {
    WelshPowell.makeGraph(n, edges);
} catch (IllegalArgumentException e) {
    // handle negative count
}

Prevention

When it happens

Trigger: Calling `WelshPowell.makeGraph(numberOfVertices, edges)` (which constructs `new Graph(numberOfVertices)`) with a negative vertex count.

Common situations: Negative vertex count from unchecked input parsing or underflowing arithmetic; reading the count from malformed config.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/6ee9256975891668. Report an issue: GitHub.