Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

DivideByZeroException — division by zero

System.DivideByZeroException signals division by zero for integers and decimal. Learn how to handle it and how this differs from float and double, which can return infinity or NaN instead.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

try { /* division or remainder */ }
catch (System.DivideByZeroException) { /* handle zero divisor */ }

System.DivideByZeroException derives from ArithmeticException. The built-in / and % operators for integers and decimal throw this exception when the divisor is zero. This also applies to a zero numerator: 0 / divisor is not valid when divisor is zero.

The float and double types behave differently: division by zero produces signed infinity or NaN, without this exception. For example, 12.0 / 0.0 produces positive infinity, while 0.0 / 0.0 produces NaN. The decimal type does not follow this rule.

If zero is an expected input, check the divisor before calculating. Use catch (DivideByZeroException) where the failure can be handled meaningfully. In the example, the variable divisor allows the exception to be demonstrated at runtime; the constant integer expression 12 / 0 is a compile-time error.

The example first catches the exception for int, then performs division with a conversion to double. The expected output is Zero divisor detected. and True on separate lines. The code is suitable for a net10.0 project; it does not require preview language features.

Examples

using System;

internal static class Program
{
    private static void Main()
    {
        int numerator = 12;
        int divisor = 0;

        try
        {
            Console.WriteLine(numerator / divisor);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Zero divisor detected.");
        }

        Console.WriteLine(double.IsPositiveInfinity((double)numerator / divisor));
    }
}

Result

Zero divisor detected.
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources