Skip to main content

Throw custom exception RangeException and handle it in JAVA.

That accepts marks of 5 subjects from users and display the average. If any value is not between 0 and 100 then throw custom exception RangeException and handle it.
CODING:
import java.util.InputMismatchException; //to use InputMismatchException class
import java.util.Scanner; //to use Scanner class
class std
{
 public static void main(String[] args){
     Scanner s1=new Scanner(System.in);
      int sum=0,temp;
      try{
       for(int i=1;i<6;i++)
        {
          System.out.print("Enter "+ i+" Subject Mark : ");
            temp=s1.nextInt();
           if(temp>=0 && temp<=100)
             sum=sum+temp;
            else
              throw new RangeException(temp);
         }
          System.out.print("The Average of Marks : " + (sum/5));
       }
        catch(RangeException e){ //catch when user not input 0 to 100
           System.out.print("Error:: " + e.getMessage());
         }
        catch(InputMismatchException e1){ //catch when user input string or charcter
           System.out.print("Error:: Input Only Numeric Value." );
        }
   }
}
class RangeException extends Exception
{
  RangeException(int msg)
   {
     super(msg + " is not between 0 to 100.");
   }
}

Comments