I am trying to add in custom exception into setters in my class objects.
While doing so, I am getting error in my Main.java
file in which the error is as follows:
error: unreported exception StudentException; must be caught or declared to be thrown
pgs.setThesisMark(-75);
In my code, the thesisMark
should be in the range of 0-100 (the input -75 is simply for testing purposes)
One way that seems to rectify the issue is by implementing try...catch...
to the setThesisMark
in main(), however it does not catch/ display the exception message.
Here are my codes:
Main.java
class Main
{
public static void main(String[] args)
{
PostGradStudent pgs = new PostGradStudent(
"Jack", "Bauer", 70);
System.out.println("Before change:");
System.out.println(pgs.getThesisMark());
pgs.setThesisMark(75);
System.out.println("After change:");
System.out.println(pgs.getThesisMark());
}
}
PostGradStudent.java
public class PostGradStudent extends Student
{
private int thesisMark;
public PostGradStudent(String firstName, String lastName,
int thesisMark)
{
// parameters for Student class
super(firstName, lastName);
this.thesisMark = thesisMark;
}
public int getThesisMark()
{
return thesisMark;
}
public void setThesisMark(int markInput) throws StudentException
{
if (markInput>0 || markInput<100)
{
thesisMark = markInput;
}
else
{
throw new StudentException("Invalid input...");
}
}
}
Student.java
public class Student
{
private String firstName;
private String lastName;
public Student(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
StudentException.java
public class StudentException extends Exception
{
public StudentException(String msg)
{
super(msg);
}
}
Additionally, is it ideal to place exception for all setter methods?