简体   繁体   中英

Use try/catch in manner of if else, but with exceptions as condition?

  • If I search in a list for an element and don't find it, I throw a NotInListException
  • otherwise I want to add it to another list

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);
}

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);
}

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));

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM