C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs » Java basic programs

Java program to handle multiple exceptions

Java multiple exceptional handling example: In this java program, we are reading two integer numbers, dividing them and handling exceptions.
Submitted by Chandra Shekhar, on January 15, 2018

Given two integer numbers and we have to divide them. If is there any exception we are handling with exception handling processes.

Example:

    Input:
    Enter First Number : 10
    Enter Second Number : 20
    Output:
    Result:0
    Explanation: There is no error 10 is divisible by 20

    Input:
    Enter First Number : 100
    Enter Second Number : 0

    Output:
    Error: Divide By ZERO
    Expiation: A number is not divisible by 0, so error is occurred

Java program:

package ExceptionHandling;

import java.util.Scanner;
import java.util.InputMismatchException;
class ExMultipleCatchBlock
{    
	public static void main(String arg[])
    {  
		try
		{
			// create object of scanner class.
			Scanner KB=new Scanner(System.in);
			
			// enter both the numbers for operation.
			System.out.print("Enter First Number : ");
			int x=KB.nextInt();

			System.out.print("Enter Second Number : ");
			int y=KB.nextInt();
			int z=x/y;
			
			// show the result.
			System.out.println("Result:"+z);
		}
		catch(InputMismatchException e)
		{
			// show if value is invalid.
			System.out.println("Invalid Input...");}
			catch(ArithmeticException e)
		{
			// show when number is divided by 0.
			System.out.println("Error:Divide By ZERO");
		}
    }
}

Output

First run:
Enter First Number : 10
Enter Second Number : 20
Result:0

Second run:
Enter First Number : 50
Enter Second Number : 12
Result:4

Third run:
Enter First Number : 100
Enter Second Number : 0
Error:Divide By ZERO

Fourth run:
Enter First Number : 10.52
Invalid Input...


Liked this article? Do share with your friends :)


COMMENTS