3

I have a static method in a utility class which assigns a value to a field.

A cutdown version of my method is:

public static void assignValue(String field, String valueToAssign){
    ...
    //code to do assign
}

If there is an error I am currently throwing an exception however I am unsure if that is the right approach because I call assignValue in a loop and I want the loop to continue even if there is an exception. So potentially many exceptions can be thrown

for(int i = 0; i < assignmentList.size(); i++){
try{
    assignValue(assignmentList.get(i).fieldName, assignmentList.get(i).fieldValue);
    }catch(AssignmentFailedException e){
        errorlist.add(e.getMessage());  
    }
}
}

Would it better better if assignValue returned an error message instead of an exception? I can then store the error and throw an exception when the list is finished

for(int i = 0; i < assignmentList.size(); i++){
String errorMessage = assignValue(assignmentList.get(i).fieldName, assignmentList.get(i).fieldValue);
if(errorMessage != ""){
    errorlist.add(errorMessage);    
}
}

If I go for the error message approach should I rename the method to let users know an error message will be returned?

user36737
  • 131
  • 1
  • 2
  • 6
  • The last one is better. If you have control over "abnormal situation" it is better to handle it manually. – Ashot Karakhanyan Feb 13 '14 at 19:34
  • 2
    Note that you should compare strings using `equals`, not `==`/`!=`. http://stackoverflow.com/questions/513832 – yshavit Feb 13 '14 at 19:36
  • @AshotKarakhanyan - I would think that, given we're all programmers here, we would always prefer to handle things automatically. Making the program stop so that the user can manually fix something is not especially desirable when it can be avoided. – Hot Licks Feb 13 '14 at 19:58

2 Answers2

0

Throwing an error or exception is not particularly efficient, since it takes time to pass the control flow to the exception handler. Try to avoid creating and throwing new ones if you can. You can even do something as simple as finding the set of situations where assignValue fails, separating them out using a conditional (rather than an exception) and printing out a message about what happened.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0

If you throw an exception it can't be easily ignored, whereas a return code can. On the other hand, a return code is easier to deal with when handling an "expected" error, and the return code is cheaper to handle (though the overhead when no error occurs may actually be higher than with the exception).

Each has its merits.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151