如果是循环,则抛出自定义异常

时间:2013-12-13 14:22:23

标签: java arrays exception for-loop custom-exceptions

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

我想要做的是返回我正在寻找的字符串的索引(如果它在数组中),否则抛出异常。

然而Eclipse说我必须返回一个int。

那么我应该将返回类型更改为void还是有其他选项?

StringNotFoundException是我编写的自定义异常。

6 个答案:

答案 0 :(得分:6)

喜欢这个

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 :(得分:4)

为什么在这里返回-1?这是代码:

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

答案 2 :(得分:2)

您未找到所需的String这一事实不足以证明Exception的使用是正确的。这不是一个特例,你知道它会发生,你在你的代码中说这个。

您的代码应该反映这一点。您不应该返回自定义值,即为-1或类似内容添加含义,这是不正确的。

有关此主题的更多信息:Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

答案 3 :(得分:2)

您需要迭代数组中的每个字符串,并且只有在没有匹配的情况下才会抛出异常。

我认为这就是你想要的:

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

    }

答案 4 :(得分:0)

怎么样:

/** 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;
}

完全避免使用例外。

答案 5 :(得分:0)

试试这个..

public int indexOf(String s) throws StringNotFoundException {

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

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

你为什么要这样做?