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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





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.