Skip to content

Java Program for Division using Try and Catch

This is a  java program for division but not the simple one. this code written using Try and Catch.
This Code is Shared By Mr. Ajit Yadav
In this program if you give wrong input, program won’t stop. It ask you whether to continue or close the program
Try and see..

Code:

//Java Program for Division using Try and Catch
import java .io.*;
public class division
{ public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

public static void main()throws IOException
{

 try
 {
   System.out.println(“Enter a 1st Number :”);
   int no1=Integer.parseInt(br.readLine());
 
   System.out.println(“Enter a 2nd Number :”);
   int no2=Integer.parseInt(br.readLine());
 
   division d=new division();
   d.div(no1,no2);
}
catch(Exception e1)
{
    System.out.println(” “+e1);
    System.out.println(“Plese Enter A Number Only”);
     System.out.println(” You Want to Continiue press (conti > 1/ closed > 2)”);
     int i=Integer.parseInt(br.readLine());
switch(i)
        {
            case 1:
            {
                main();
            }
            case 2:
            {
                System.exit(0);
            }
        }
}
}
public static void div(int no1,int no2)throws IOException
{
  try
  {
      double res=no1/no2;
      System.out.println(“Division : “+no1+” / “+no2+” =  “+res);
       System.out.println(” You Want to Continiue press (conti > 1/ closed > 2)”);
        int i=Integer.parseInt(br.readLine());
        switch(i)
        {
            case 1:
            {
                main();
            }
            case 2:
            {
                System.exit(0);
            }
        }
    }
    catch(Exception e)
    {
        System.out.println(” “+e);
        System.out.println(“Number Can Not Div By 0 :”);
        System.out.println(” You Want to Continiue press (conti > 1/ closed > 2)”);
        int i=Integer.parseInt(br.readLine());
        switch(i)
        {
            case 1:
            {
                main();
            }
            case 2:
            {
                System.exit(0);
            }
        }
    }
 
}
}

Sample Output:

Comment bellow for Query and Feedback 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!