System.DivideByZeroException: Attempted to divide by zero in Java

In this Java program, we are going to learn how to handle divide by zero run time error in Java.

Error Message:

System.DivideByZeroException: 'Attempted to divide by zero.'

Error Description:

Whenever we are going to divide any number with zero, this error will occur.


using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //try
            //{
                int firstNumber = 3, secondNumber = 0;

                secondNumber = firstNumber / secondNumber;

                Console.Read();
            //}
            //catch(Exception e)
            //{
            //    Console.Write(e.Message);
            //    Console.Read();
            //}


        }
    }
}


Error Solution: 

We need to handle this runtime error in the exception block as shown below.

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int firstNumber = 3, secondNumber = 0;

                secondNumber = firstNumber / secondNumber;

                Console.Read();
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                Console.Read();
            }


        }
    }
}


Output:



Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar