Netbeans给我一个错误信息,但它按我的意愿工作

时间:2013-09-19 17:39:23

标签: java function netbeans return

我有一个子类,其中包含一个返回float的函数。我在try catch语句中调用该函数,如果if语句失败并且else捕获它我希望该函数“崩溃”返回注意这样return;

这是该功能:

float calc(... some arguments ...) {
    ...

    if (operator.equals("+")) number = num1+num2;
    else if (operator.equals("-")) number = num1-num2;
    else if (operator.equals("*")) number = num1*num2;
    else if (operator.equals("/")) number = num1/num2;
    else return; // Here Netbeans gives me an error saying "Missing return value"

    return number;
}

现在这个函数在try中被调用了,如果else被执行,我希望函数“崩溃”并转到catch语句并给用户一个错误消息。这完全按照我想要的方式工作,但为什么Netbeans会给我一个错误?还有另一种方法吗?

3 个答案:

答案 0 :(得分:4)

我认为你不希望它“崩溃”,但你需要指出某种错误。因为该方法没有返回void,所以返回任何内容都不是编译器错误。

相反,抛出IllegalArgumentException

else throw new IllegalArgumentException("Illegal operator: " + operator);

请确保在结尾处实际返回有效值:

return number;

答案 1 :(得分:2)

你不能从这个函数return;(返回void),因为那不是你的方法的声明方式。当您将其声明为float calc时,您承诺将始终返回float值。

此外,你已经在try-catch块中,所以你不想再回复任何东西 - 你想要做的就是抛出一些异常来捕获。确保您抛出的异常适合您的特定情况。因为我不知道你的函数是做什么的,所以我不应该说出你应该抛出什么样的异常。

public float calc(float[] args) throws Exception { // Use a more specific Exception!
    // do stuff
    if (somethingIsWrong) {
        throw new Exception("something is wrong!");
    }
    return number; // Always return a float!
}

答案 2 :(得分:2)

使用例外。

离。

如果“operator”是您的参数之一,请使用IllegalArgumentException:

function calc(... some arguments ...) {
    ...

    if (operator.equals("+")) number = num1+num2;
    else if (operator.equals("-")) number = num1-num2;
    else if (operator.equals("*")) number = num1*num2;
    else if (operator.equals("/")) number = num1/num2;
    else throw new IllegalArgumentException();
}

或者如果你想要更具体的方法扩展RuntimeException,就像 MyAppIllegalOperatorException,并抛出/捕捉其中一个