在某些情况下 java 中预期没有 return 类型的函数处理 return

handling return from function where no return type is expected in some case in java

我写了一段 code:In 这段代码我们正在调用 validitem 函数来检查 passes 参数是否是某个有效项目或 not.If 它是有效项目,我想 return 我想中止处理的其他项目表明它无效 item.Please 建议解决下面的初始代码 writtern,如果我们 return anything.And 如何处理我们不想 anything.And 的情况=20=] null,那么如何以及在哪里捕获异常?

public void constructdata(){
    String foo = validitem(param);
    //code to avoid processing if null is returned
}
public validitem(String item){
    if(item.equals("Apple"){
        return item;
    }
    if(item.equals("Ball"){
        return item;}
    return null;
}

如果您希望 validitem() 仍为 return null,如果是,则抛出异常:

String foo = validitem(param);
if ( foo != null ) {
    container.putField(key, foo);
} else {
    throw new Exception();
}

如果您只想让 validitem() 成为 return 一个有效值,否则抛出异常:

public void constructdata(){
    try {
        container.putField(key, validitem(param));
    } catch (Exception e) {
        // Handle exception
    }
}

public validitem(String item) throws Exception {
    if (item.equals("Apple") {
        return item;
    }
    if (item.equals("Ball") {
        return item;
    }
    throw new Exception("Error message");
}

您应该使用比 Exception() 更具体的例外。我只是用它来演示逻辑。

尽可能避免 returning null,因为它会导致错误,因此您可以 return Java8 Optional. If you are not using java8 there is an equivalent in the guava 库。返回一个 Optional 会迫使客户端考虑如何处理没有 returned.

的情况