System.DivideByZeroException Class

System Namespace

Syntax


public sealed class DivideByZeroException : ArithmeticException

Remarks

A DivideByZeroException is thrown when an attempt is made to divide an integer or decimal number by zero. This exception inherits from ArithmeticException, which in turn inherits from SystemException.

The following conditions cause a DivideByZeroException to be thrown:

Note: In the .NET Framework, integer division by zero throws a DivideByZeroException. However, in the .NET Core and .NET 5+ for C#, integer division by zero throws an ArithmeticException, not a DivideByZeroException. For consistent behavior, you might consider catching ArithmeticException.

Constructors

Name Description
DivideByZeroException() Initializes a new instance of the DivideByZeroException class.
DivideByZeroException(string message) Initializes a new instance of the DivideByZeroException class with a specified error message.
DivideByZeroException(string message, Exception innerException) Initializes a new instance of the DivideByZeroException class with a specified error message and a reference to the inner exception that is the cause of the current exception.

Example

The following C# code example demonstrates how to handle a DivideByZeroException.


using System;

public class Example
{
    public static void Main()
    {
        int a = "10";
        int b = "0";
        int result;

        try
        {
            result = a / b;
            Console.WriteLine("Result: {0}", result);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Caught an exception: {0}", ex.Message);
            Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
        }
        catch (ArithmeticException ex) // Recommended for broader compatibility
        {
            Console.WriteLine("Caught an arithmetic exception: {0}", ex.Message);
        }
        finally
        {
            Console.WriteLine("Execution finished.");
        }
    }
}
                

See Also