I am writing a method which contains if else statements, but also a return keyword. Now, I'm writing something like this:
public boolean deleteAnimal(String name) throws Exception{
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
else throw new Exception("Animal doesn't exist");
return hTable.get(name) == null;
}
I'm new in java and this is my first time trying to learn a programming language. I read that the 'else' statement excecutes always if the if condition is false.
Now, if these are false:
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
Shouldn't the else part always excecute?
else throw new Exception("Animal doesn't exist");
I noticed this since this method is returning true/false, and it seems like it's ignoring the else part, even when the conditions above it are false.
elsewill fire if all other conditionals--i.e.if,if else--arefalse. It does not always execute. Think about it like this:If it is raining, then I carry my umbrella; else if it is snowing, then I wear my parka; else I wear shorts and a tshirt."Animal doesn't exist",exists(name)needs to be false, not the conditions in the first if-condition.ifcondition was false, not all other conditionals.