using System;
class Program
{
static void Main()
{
//// This expression evaluates to 100 / 0, which throws.// ... You can check the denominator in a separate step.//
int result = 100 / int.Parse("0");
Console.WriteLine(result);
}
}Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.Main() in ... Program.cs:line 11
A discussion. If you try to divide by a constant zero (the number 0 in source code), the program will fail to compile. It can never be executed.
Note The compiler does this to reduce errors in finished programs that were not tested.
Info This can be confusing—the system uses different compilation phases. The divide by zero error can be detected on different levels.
Division by constant zero
A summary. We demonstrated the DivideByZeroException in the C# language, which is detected at two different stages: compile-time and runtime. This exception is built into the C# language itself.
A final note. To avoid the divide by zero exception, you must check the denominator against the zero value. This numeric check will be much faster than having an exception thrown in the runtime.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 20, 2021 (edit).