divide by zero in csharp

You cannot divide by zero in C#. Doing so will result in a runtime error.

However, you can handle the error by catching the DivideByZeroException that is thrown when a division by zero is attempted. Here's an example:

main.cs
int dividend = 10;
int divisor = 0;
int result;

try
{
    result = dividend / divisor;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Division by zero error: " + ex.Message);
}
191 chars
13 lines

In the above example, since the divisor variable has a value of zero, a DivideByZeroException is thrown. We catch the exception and display an error message to the user indicating that a division by zero error occurred.

Note that it is generally not recommended to purposely divide by zero in your code. Instead, you should check if the divisor is zero before performing the division operation to avoid the error altogether.

gistlibby LogSnag