Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exception in constructor

Tags:

java

public class AnimalException extends Exception {
    public AnimalException(String error) {
        super(error);
    }
}

public class Zoo {
    private String animal;
    private String food;

    public Zoo (String animal, String food) throws AnimalException {
        this.animal = animal;
        if (findWord(animal, "wolf")) {
            throw new AnimalException("This animal is a predator.");
            //something ought to be done here, I reckon
        }
        else {
            this.food = food;
        }


    }

    public static boolean findWord(String word, String find) {
        int total = 0;
        int idx = 0;
        while ( (idx = word.indexOf(find, idx))!= -1 ) {
            total++;
            idx++;
        }
        if (total == 0) {
            return false;
        }
        else {
            return true;
        }
}

What I would like to do is when a wolf is caught in the constructor the value for foodis changed automatically to something else. I did try using getter-setters, however, I get the error of unreachable code. What do I do?

like image 748
AlvinL Avatar asked Oct 19 '22 11:10

AlvinL


1 Answers

If you want some specific logic to be performed when you detect a "wolf", an exception is not the right way. You should only throw an exception if the construction of the instance should fail when you find a "wolf".

public Zoo (String animal, String food) {
    this.animal = animal;
    if (findWord(animal, "wolf")) { 
        // put whatever logic you wish here
    }
    else {
        this.food = food;
    }
}
like image 115
Eran Avatar answered Oct 22 '22 01:10

Eran