System Namespace
public sealed class DivideByZeroException : ArithmeticException
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:
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. |
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.");
}
}
}