Fitz Fitz - 6 months ago 13
Java Question

Java : Proper way a method() should handle a bad call

I am often confronted to this question. Let's see a quick example, I got this simple method : It retrieves the position of a

in a

public int getStringPosition(String s, String[] text) {
for (int i = 0; i < text.length; i++) {
if (text[i].equals(s)) {
return i;
return text.length;

But what if the String isn't in the array? Here, it returns the size of the array (an
that couldn't come from a normal use of the method). It could as well return
. I wish it would return null but that doesn't seem to be possible.

Anyway, this method will be used in the same class by some other methods. My question is pretty general, how to handle the cases where you can't return what is expected?


If the inability to find the string constitutes an error, an exceptional condition, then you should throw some exception. E.g.,

throw new RuntimeException("String not found");

If the inability to find the string is a normal situation that the caller would want to handle in the normal flow of the code, then you should use a special return value. In this case, where no normal return value could be negative, the convention is to return -1; as String.indexOf, List.indexOf, and similar methods do. In that case, you could actually implement your method body with a single line:

return java.util.Arrays.asList(text).indexOf(s);