TheAlgorithms/C-Sharp · error · DivideByZeroException

Cannot divide by zero

Error message

Cannot divide by zero

What it means

EvaluateOperator throws DivideByZeroException when the '/' operator is applied and the second operand (b, the divisor) is 0. The library explicitly checks this instead of letting integer division throw.

Solutions

  1. Check operands before evaluation, or catch DivideByZeroException around the evaluation call.
  2. Restructure the expression to guard division, or reject zero divisors at input time.
  3. Return a sentinel/nullable result when division by zero is possible in your domain.

Example fix

// before
int r = evaluator.PostfixExpressionEvaluation("5 0 /"); // throws
// after
try { int r = evaluator.PostfixExpressionEvaluation("5 0 /"); }
catch (DivideByZeroException) { /* handle: report invalid expression */ }
Defensive patterns

Strategy: try-catch

Try / catch

try { int r = evaluator.PostfixExpressionEvaluation(postfix); } catch (DivideByZeroException) { /* divisor evaluated to 0; handle gracefully */ }

Prevention

When it happens

Trigger: Evaluating postfix like "5 0 /" where the divisor evaluates to zero.

Common situations: Dynamic expressions with computed denominators that happen to be zero; user-supplied expressions dividing by a variable value of 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/0f46d4ccb649bb01. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Stack/InfixToPostfix.cs:164

                }

                postfix.Append(stack.Pop());
            }
        }

        private static void EvaluateOperator(Stack<int> stack, char op)
        {
            if (stack.Count < 2)
            {
                throw new InvalidOperationException("Insufficient operands");
            }

            int b = stack.Pop();
            int a = stack.Pop();

            if (op == '/' && b == 0)
            {
                throw new DivideByZeroException("Cannot divide by zero");
            }

            int result = op switch
            {
                '+' => a + b,
                '-' => a - b,
                '*' => a * b,
                '/' => a / b,
                '^' => (int)Math.Pow(a, b),
                _ => throw new InvalidOperationException($"Unknown operator {op}"),
            };

            stack.Push(result);
        }

        private static void ValidateInfix(string expr)
        {
            if (string.IsNullOrEmpty(expr) || string.IsNullOrWhiteSpace(expr))

View on GitHub (pinned to 96e2905cab)