java中无法访问的语句返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20127402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:21:23  来源:igfitidea点击:

Unreachable statement return in java

javaandroidlist

提问by gmendes

I have a method what return a list, but when i run the code, appears Unreachable statement this method come from a aidl file and generate a map with the return.

我有一个返回列表的方法,但是当我运行代码时,出现 Unreachable 语句,此方法来自 aidl 文件并生成带有返回值的映射。

code bellow:

代码如下:

List<String> list = new ArrayList<String>();

Public List<String> setMethod(Map map) {
    ContentValues cv = null;
    Iterator i = map.keySet().iterator();
    Iterator j = map.values().iterator();

    if(map.isEmpty() || map == null) {
        return null;
    } else {
        try {
            while(i.hasNext()) {
                String str = (String) i.next();
                Long l = (Long) j.next();
                list.add(str);
                cv.put(Storage.STR, str);
                if(Provider.insert(Storage.Table, cv) < 0) {
                   return null;
                }
            }
            if(list.isEmpty() || list == null) {
                return null;
            } else {
                return mPathList;
            }
        } catch (Exception e) {
            return null;
        }
   return list;
}

Anybody can give me a light what i can make for dolve it?

任何人都可以给我一盏灯,我可以为它做些什么?

采纳答案by Habib

You are returning from tryblock as well as catch, so the last return statement will never be reached.

您正在从tryblock 和返回catch,因此永远不会到达最后一个 return 语句。

Your code has multiple return paths. You are returning from first ifstatement if your condition is met, in elsepart you have tryblock. In tryyou are returning based on ifas well as else, so if no exception occurs you are guaranteed to return from tryblock, in case of exception you have a catchstatement and you are returning from there as well. So there is no possibility that your code will continue further. Hence the last returnstatement is unreachable.

您的代码有多个返回路径。if如果满足您的条件,您将从第一个语句返回,else部分您有try块。在try您返回的基础上if以及else,因此如果没有发生异常,您可以保证从try块返回,如果出现异常,您有一个catch语句并且您也从那里返回。所以你的代码不可能继续下去。因此,最后一条return语句无法访问。

回答by Adam Arold

Just follow through your code. The last returnstatement will never be run because every other branch before that leads to an other returnstatement.

只需按照您的代码进行操作。最后一条return语句永远不会运行,因为在此之前的每个其他分支都会导致另一个return语句。