I want to throw an exception in order to let the user know that the age value input should be between 1 and 120. Find below the example.
Is there a better way to throw an exception?
public class Lesson18Encapsulation3 {
private int age;
private String name;
private int salary;
public int getAge() {
return age;
}
public void setAge(int age) {
if ( age < 0 && age >= 120)
this.age = age;
throw new IllegalArgumentException (" age can not be negative or more than 120");
//getters and setters
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Lesson18Encapsulation4 {
public static void main(String[] args) {
Lesson18Encapsulation3 emp = new Lesson18Encapsulation3();
emp.setAge(220);
emp.setName("None");
System.out.println( "age : " + emp.getAge());
System.out.println( "name : " + emp.getName());
}
}
this.age = age;. You may also consider using Java Validation Api, an example here : baeldung.com/javax-validation