×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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 »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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