C# - DivideByZeroException Exception Example

Learn about the DivideByZeroException exception and demonstrating the example of DivideByZeroException exception in C#. By Nidhi Last updated : April 03, 2023

DivideByZeroException Exception

Here, we are demonstrating the divide by zero exception. We will divide a number by 0 then the program will exception that will be caught in the "catch" block.

C# program to demonstrate DivideByZeroException exception

The source code to demonstrate the DivideByZeroException exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - DivideByZeroException Exception Example.

using System;

class ExceptionDemo
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 0;
        int c = 0;

        try
        {
            c = a / b;
            Console.WriteLine(c);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output

Attempted to divide by zero.
Press any key to continue . . .

Explanation

In the above program, we created a class ExceptionDemo that contains the Main() method. In the Main() method, we created three variables a, b, and c initialized with 10, 0, and 0 respectively.

try
{
    c = a / b;
    Console.WriteLine(c);
}
catch (DivideByZeroException e)
{
    Console.WriteLine(e.Message);
}

In the above code, we divided a variable a by variable b, the value of variable b is 0, then the program will generate DivideByZeroException that will be caught in the "catch" block and then print the exception message using "Message" property on the console screen.

C# Exception Handling Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.