Home » Java programs » Java basic programs

Java program to divide two numbers and catch the exception, if divisor is 0



In this java program, we are reading two integer numbers and dividing them also checking the exception. Program will through an error if second number (divisor) will be zero (0).
Submitted by Chandra Shekhar, on January 15, 2018

Given two integer numbers and we have to divide them by checking exception if divisor is 0.

Example:

    Input:
    Enter first number : 70
    Enter second number : 5

    Output:
    Result:14 
    Explanation: There is no exception because divisor is not 0

    Input:
    Enter first number : 100
    Enter second number : 0

    Output:
    Error:/ by zero

    Explanation: Error:java.lang.ArithmeticException: / by zero

Java program:

package ExceptionHandling;

import java.util.Scanner;

class Ex1
{  
	public static void main(String arg[])
    {  
		try
		{
			// declare and initialize here.
			int a,b,c;
			Scanner KB=new Scanner(System.in);
			
			// input numbers here.
			System.out.print("Enter first number : ");
			a=KB.nextInt();
       
			System.out.print("Enter second number : ");
			b=KB.nextInt();
       
			//throw to catch
			c=a/b;
			System.out.println("Result:"+c);
		}
		catch(ArithmeticException e)
		{
			System.out.println("Error:"+e.getMessage());
			System.out.println("Error:"+e);
		}
		// here program ends.
		System.out.println("End of Program...");
	}
}

Output

First run:
Enter first number : 100
Enter second number : 0
Error:/ by zero
Error:java.lang.ArithmeticException: / by zero
End of Program...

Second run:
Enter first number : 70
Enter second number : 5
Result:14
End of Program...





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.