The problem with your view is that the throw exception rejection goes beyond the blocks and looks for a try-catch that can handle the exception. In your case
void foo() { if (somethingbad()) { throw new exception(); bar();
If you throw an exception in the constructor, and the exception leaves the function because there is no try-catch in the constructor for this exception, the construction of this object fails. So, if your Zoo forbids having a wolf as an animal, you should throw an exception (this way Zoo will never be created at all).
public Zoo (String animal, String food) throws AnimalException { this.animal = animal; if (findWord(animal, "wolf")) { throw new AnimalException("This animal is a predator."); } else { this.food = food; } } void foo() { Zoo myZoo; try { myZoo = new Zoo("wolf", "meat"); } catch (AnimalException ex) { System.out.println(ex.toString()) }
However, if you want to have predators in Zoo , but with a warning to all visitors, you should just show a warning.
public Zoo (String animal, String food) throws AnimalException { this.animal = animal; this.food = food; if (findWord(animal, "wolf")) { System.out.println("Beware, we have a predator in zoo"); } }
Also, did you know that your Zoo can only contain one animal and one food?
One more thing. Your findWord(String, String) method is too complicated. Java contains many useful classes and functions, so we do not stop to write code each time again and again. Searching for a substring of a word is really useful and a favorite feature. Take a look at indexOf(String) . It is designed exactly for your purpura and is probably implemented similarly.
source share