In: Computer Science
27) Consider the student class. There is a method setSemesterGrade(int grade) In that method write code to throw a new IllegalStateException if the average is less than 0 And an IndexOutOfBoundsException if the average is > 0
28) Consider a student represented by the variable s1 and we are trying to set the average of s1. Write a try catch routine to catch either error listed above try { s1.setSemesterGrade(-30); s1.setSemesterGrade(200);
Program:
class IllegalStateException extends Exception
{
IllegalStateException(String str)
{
super(str);
}
}
class IndexOutOfBoundsException extends Exception
{
IndexOutOfBoundsException(String str)
{
super(str);
}
}
class Student
{
//int grade - as given in the question but i think its an average,
treated as
void setSemesterGrade(int grade) throws IllegalStateException,
IndexOutOfBoundsException
{
if(grade<0)
{
throw new IllegalStateException("Illegal state exception!!");
}
else if(grade>0)
{
throw new IndexOutOfBoundsException("Index out of bound
exception!!");
}
else
{
System.out.println("Grade: "+grade);
}
}
public static void main(String args[])
{
Student s1=new Student();
try
{
s1.setSemesterGrade(-30);
s1.setSemesterGrade(200);
}
catch(IllegalStateException e1)
{
System.out.println("The average is less than 0");
}
catch(IndexOutOfBoundsException e1)
{
System.out.println("The average is greater than 0");
}
}
}
Output: