TheAlgorithms/C-Sharp · error · InvalidOperationException

Edge weight cannot be zero.

Error message

Edge weight cannot be zero.

What it means

AddEdge rejects edges whose weight is exactly 0.0 via ThrowIfWeightZero, because 0.0 is used internally as the sentinel meaning 'no edge exists' in the weight matrix. A zero weight is therefore indistinguishable from a missing edge and is explicitly forbidden.

Solutions

  1. Use a non-zero weight (e.g. 1.0 for unweighted semantics).
  2. Guard the call: only add the edge when the weight is not 0.0.
  3. If a zero-cost edge is genuinely needed, shift weights (e.g. add 1 to all) or use a different graph structure.

Example fix

// before
graph.AddEdge(a, b, weightB - weightA); // both equal -> 0.0 -> throws
// after
var w = weightB - weightA;
if (w != 0) graph.AddEdge(a, b, w);
Defensive patterns

Strategy: validation

Validate before calling

static bool IsValidEdgeWeight(double w) => !w.Equals(0.0d);
// call: if (!IsValidEdgeWeight(w)) throw new ArgumentException("zero weight");

Type guard

static bool IsNonZeroWeight(double w) => !w.Equals(0.0d);

Try / catch

try { graph.AddEdge(u, v, w); }
catch (InvalidOperationException ex) when (ex.Message == "Edge weight cannot be zero.") { /* skip or remap weight */ }

Prevention

When it happens

Trigger: graph.AddEdge(v1, v2, 0.0) or AddEdge with a computed weight that evaluates to 0.0 (e.g. multiplying by zero, subtracting equal values).

Common situations: Modeling unweighted graphs with weight 0 instead of 1, computing weights as differences that cancel to zero, or deserializing edge lists where missing weights default to 0.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/4ac14f16683e5174. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Graph/DirectedWeightedGraph.cs:206

            return adjacencyMatrix[startVertex.Index, endVertex.Index];
        }

        return 0;
    }

    private static void ThrowIfNegativeCapacity(int capacity)
    {
        if (capacity < 0)
        {
            throw new InvalidOperationException("Graph capacity should always be a non-negative integer.");
        }
    }

    private static void ThrowIfWeightZero(double weight)
    {
        if (weight.Equals(0.0d))
        {
            throw new InvalidOperationException("Edge weight cannot be zero.");
        }
    }

    private static void ThrowIfEdgeExists(double currentEdgeWeight)
    {
        if (!currentEdgeWeight.Equals(0.0d))
        {
            throw new InvalidOperationException($"Vertex already exists: {currentEdgeWeight}");
        }
    }

    private void ThrowIfOverflow()
    {
        if (Count == capacity)
        {
            throw new InvalidOperationException("Graph overflow.");
        }
    }

View on GitHub (pinned to 96e2905cab)