0

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();
    }
}
  • It's fine. I would usually make sure it's a runtime exception, though. Having to deal with checked exceptions when constructing objects is just annoying. – Michael Feb 27 '19 at 14:13

1 Answers1

0

I would say for a student project this is safe. However, that is as LONG as you know WHAT the error is, and your program handles it accordingly. You don't want to be throwing exceptions if you don't understand them :)

However, putting that in the constructor is totally okay!

artemis
  • 6,857
  • 11
  • 46
  • 99