ADVERTISEMENT
ADVERTISEMENT

C# program to demonstrate DivideByZeroException exception

Here, we are going to learn about the DivideByZeroException exception and demonstrating the example of DivideByZeroException exception in C#.
Submitted by Nidhi, on September 16, 2020

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

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 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 »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.