Q:

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

belongs to collection: Java Basic Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to handle multiple exceptions... >>
<< Java program to read marks between 1 to 100 (An Ex...