I need to check whether my data which I pass to constructor are valid during constructing object (my student project, I need only advice, not solutions). Is a good idea to check it in constructor? I have method where I checking cases and throw Exceptions. I marked my main method that it can throw Exception. I don't know how I can check it in other way. Can you give me some advice?
public class Triangle {
private double height;
private double base;
private double sideB;
private double sideC;
public Triangle(double height, double base, double sideB, double sideC){
this.height = height;
this.base = base;
this.sideB = sideB;
this.sideC = sideC;
isValid();
}
private void isValid(){
try{
if(height <= 0){
throw new Exception("Wysokość musi być większa od 0!");
}
else if(base<=0 || sideB <=0 || sideC <= 0){
throw new Exception("Rozmiar boku musi być większy od 0!");
}
else if(base + sideB <= sideC){
throw new Exception("Trójkąt nie istnieje!");
}
else if(base + sideC <= sideB){
throw new Exception("Trójkąt nie istnieje!");
}
else if (sideB + sideC <= base){
throw new Exception("Trójkąt nie istnieje!");
}
}catch(Exception e){
e.printStackTrace();
}
}