Reputation: 1293
I achieved this by
try {
element = actualList.find("foo");
anotherList.append(element);
}
catch (NotInListException e) {
}
Is this usage okay? Or should I refactor it with smth like this:
if ((element = actualList.find("foo")) != null) {
anotherList.append(element);
}
Upvotes: 3
Views: 190
Reputation: 2566
Your second example is much cleaner and easier to read. You didn't provide any details, but i guess not finding a value in your search should not be considered an exceptional situation.
Using Java 8 you could even think about returning an Optional
and add the result like this:
actualList
.find("foo")
.ifPresent(v -> anotherList.add(v));
Upvotes: 1
Reputation: 14705
This is a matter of style if you disregard the small runtime penalties given by the exception handlers.
One could design a stack type like
try{
while(true){
try{
stack.pop();
catch(StackElement e){
processElement(e);
}
}
catch(EmptyStackException ese){
// probably not much to do here.
}
Consensus is, for reasons of readability and common sense, that the usual if
condition makes things easier to understand. The exception mechanism should be used for exceptional situations, not for regular flow control.
In your particular example of find, you have two cases, none of them are out of the ordinary. So an exception is probably unnecessary.
1 - didn't find the element.
2 - found the element.
Case 2 requires extra attention as your version of find also wants to return the actual element.
1 || 2 is a boolean situation. So that should not be an element. find() for case 2 should be an element.
I've always disliked the return null for a non value. It makes for ugly code. Just recall
void f(BufferedReader br){
String line;
while( (line = br.readLine()) != null)
Better is to separate the boolean from the element.
if( list.has(foo) ){
E element = list.get(foo);
}
Upvotes: 2
Reputation: 76454
I believe that your code should follow logical principals. If the question is to throw or not to throw a NotInListException, then the perequisite question to answer is: is the element not being in the list an exceptional case? Do we actually expect that element to be in the list? If the answer is yes, then the case when the element is not in the list is exceptional, hence, throwing an exception makes sense. Otherwise it should be an if-else logic.
Upvotes: 0
Reputation: 30819
I would recommend writing something like this:
List<String> elements; //get the list
try{
if(elements.contains("foo")){
anotherList.add("foo");
}else{
throw new NotInListException("Element not present");
}
}catch(NotInListException ex){
//do something
}
Upvotes: -1