Skip to main content

Create Package and Exceptions handling with Throws keyword in JAVA

Create package Calc and TestNum class.In class getdata() method with declare throws keyword.After create second java file and import Calc package with TestNum Class and handle exception handling.
Calc >TestNum.java 
CODING:
package Calc;
import java.util.*;
public class TestNum {
int[] a=new int[10];
int temp=0,flag=0,count=0;
Scanner sc=new Scanner(System.in);
public void getdata()throws Exception{
for(int k=0;k<10;k++){
System.out.print("Enter the Number :");
temp=sc.nextInt();
flag=0;
         for(int i=2;i<=temp/2 && flag==0;i++){if(temp%i==0)flag=1;}   
            if(flag==0)
           throw new Exception("Not Input Prime Number");
            else{
      for(int i=0;i<k && flag==1;i++){
    if(a[i]==temp){
    flag=0;
    count+=1;
    k-=1;
    if(count==5)
    throw new Exception("Five time same number input");
    }
    }
          if(flag==1){
          System.out.println(k);
    a[k]=temp;
          }
  }
   }
}
public void disp(){
for(int i=0;i<10;i++){
System.err.print(a[i]+" ");
}
}
}
main.java 
CODING:              
import Calc.TestNum;
public class main{
  public static void main(String[] args){
TestNum obj=new TestNum();
          try{
         obj.getdata();
        obj.disp();
           }
          catch(Exception e){
                 System.out.print("Error  "+ e.getMessage());
           }
  }
}

Comments