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

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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