Throwing custom Exceptions, if for loop

376 views Asked by At
public class StringArray {
    private String strArr[];

    public StringArray(int capacity) {
       strArr = new String [capacity];
    }

    public int indexOf(String s) throws StringNotFoundException {
        for(int i=0;i<strArr.length ;++i) {
            if (strArr[i].equals(s)) {
                return i;
            } else {
                throw new StringNotFoundException();
            }
        }
    }
}

What I want to do is to return the index of the string I'm looking for if it's in the array, to throw an exception otherwise.

However Eclipse says I've got to return an int.

So should I just change the return type to void or are there other options?

StringNotFoundException is a custom exception I've made up.

6

There are 6 answers

0
Prabhakaran Ramaswamy On BEST ANSWER

do like this

public int indexOf(String s) throws StringNotFoundException {
     for(int i=0;i<strArr.length ;++i) {
         if (strArr[i].equals(s)){
             return i;
         }
     }
     throw new StringNotFoundException();
}
0
Alberto Zaccagni On

The fact that you're not finding the String you're looking for is not enough to justify the usage of Exception. It's not an exceptional case, you know it's going to happen, you're saying that in your code.

Your code should reflect this. You should not return custom values, that is adding a meaning to things like -1 or the likes, which is not correct.

More on the subject: Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

0
Nishan On

You need to iterate through each string in the array and only if nothing matches, throw the exception.

I think this is what you want :

public int indexOf(String s) throws StringNotFoundException {
        for (int i = 0; i < strArr.length; ++i) {
            if (strArr[i].equals(s)) {
                return i;
            } 

        }
        throw new StringNotFoundException();

    }
0
claymore1977 On

How about:

/** Returns index of String s in array strArr.  Returns -1 if String s is not found. */
public int indexOf(String s) {
        for(int i=0;i<strArr.length ;++i) {
            if (strArr[i].equals(s)){
             return i;
            }
        return -1;
}

Avoids using an exception altogether.

0
LHA On

Why return -1 here? here is the code:

public int indexOf(String s) throws StringNotFoundException {
    for(int i=0; i<strArr.length ;++i) {
        if (strArr[i].equals(s)) {
            return i;
        }
    }
    throw new StringNotFoundException();
}
1
HybrisHelp On

Try this..

public int indexOf(String s) throws StringNotFoundException {

       int index = Arrays.binarySearch(strArr ,s);

        if( index > 0)
             return index;
        else
            throw new StringNotFoundException();
    }

Why you want to do this ? .