Class

ArithmeticException

Namespace: System

Summary

Represents errors that occur during arithmetic operations, such as overflow. This is the base class for exceptions that are thrown for arithmetic errors.

Description

The .NET Framework throws an ArithmeticException when an arithmetic operation in a C# or Visual Basic program results in an overflow or a division-by-zero error.

The following arithmetic operations can cause an ArithmeticException:

  • Integer overflow.
  • Division by zero.
  • Conversions from a larger integral type to a smaller integral type that result in overflow.
  • Conversions from Double or Single to an integral type that result in overflow.
  • Conversions from Decimal to an integral type that result in overflow.

When an arithmetic operation overflows, the .NET Framework detects the overflow and throws an ArithmeticException. The program execution is interrupted, and the exception is handled by the nearest appropriate exception handler.

Inheritance

Syntax

public class ArithmeticException : Exception
Public Class ArithmeticException
 Inherits Exception
End Class

Remarks

ArithmeticException is a base class for exceptions that are thrown for arithmetic errors.

You can catch ArithmeticException to handle overflow or division-by-zero errors.

It is generally preferable to catch more specific exceptions, such as DivideByZeroException, when possible.

Examples

Integer Overflow Example (C#)

This example demonstrates how an integer overflow can throw an ArithmeticException.

using System;

public class Example
{
    public static void Main()
    {
        checked
        {
            try
            {
                int a = int.MaxValue;
                int b = 1;
                int sum = a + b; // This will cause an overflow
                Console.WriteLine($"Sum: {sum}");
            }
            catch (ArithmeticException ex)
            {
                Console.WriteLine($"An arithmetic error occurred: {ex.Message}");
            }
        }
    }
}

Division by Zero Example (C#)

This example demonstrates a division by zero error.

using System;

public class Example
{
    public static void Main()
    {
        try
        {
            int numerator = 10;
            int denominator = 0;
            int result = numerator / denominator; // This will cause a division by zero
            Console.WriteLine($"Result: {result}");
        }
        catch (ArithmeticException ex)
        {
            Console.WriteLine($"An arithmetic error occurred: {ex.Message}");
            // You could also specifically catch DivideByZeroException:
            // if (ex is DivideByZeroException) { Console.WriteLine("Caught DivideByZeroException."); }
        }
    }
}