Q:

C# program to demonstrate DivideByZeroException exception

0

C# program to demonstrate DivideByZeroException exception

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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

//C# Program to Demonstrate DivideByZeroException Exception.

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 ab, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now