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.
Program:
The source code to demonstrate the DivideByZeroException exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
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.
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.