DivideByZeroExceptionUnderstand the DivideByZeroException, and review ways to avoid this error.
This page was last reviewed on Dec 20, 2021.
DivideByZeroException. In a C# program, a DivideByZeroException is thrown. This indicates that a statement attempted to evaluate a division by zero.
Compiler notes. The C# compiler can detect divisions by the constant zero value. The runtime can throw the exception during program execution.
An example. This program shows how an exception is thrown by the execution engine when you divide an int by zero. It prints the exception's data.
Info It uses a zero value determined at runtime through a parsing method, so that the program can be correctly compiled.
Int, uint
Then We discuss issues related to the compiler system and dividing a number by zero.
Info The division is evaluated to 100 / 0, which cannot be done. The program terminates by throwing a DivideByZeroException.
Tip To avoid the exception, you must always test the denominator value for zero. Alternatively you can use try and catch.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 20, 2021 (edit).
© 2007-2023 Sam Allen.