2

I have a subclass which contains a function which returns a float. I call that function in a try catch statement, if the an if statement fails and the else catches it I want that function to "crash" by returning noting like this return;

Here is that function:

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

Now this function is getting called in a try and I if the else gets executed I want the function to "crash" and go to the catch statement and give the user an error message. This works exactly the way I want it but why does Netbeans give me an error?? Is there another way to do this?

4

3 回答 3

4

我认为您不希望它“崩溃”,但您需要指出某种错误。因为该方法没有返回void,所以什么也不返回是编译器错误。

相反,抛出一个IllegalArgumentException.

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

只要确保你在最后返回一个有效值:

return number;
于 2013-09-19T17:42:03.493 回答
2

你不能return;使用这个函数(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!
}
于 2013-09-19T17:43:22.440 回答
2

为此使用例外。

前任。

如果“操作员”是您的参数之一,请使用 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,并抛出/捕获其中一个

于 2013-09-19T17:46:59.343 回答