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
Unreachable statement return in java
提问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 try
block as well as catch
, so the last return statement will never be reached.
您正在从try
block 和返回catch
,因此永远不会到达最后一个 return 语句。
Your code has multiple return paths. You are returning from first if
statement if your condition is met, in else
part you have try
block. In try
you are returning based on if
as well as else
, so if no exception occurs you are guaranteed to return from try
block, in case of exception you have a catch
statement and you are returning from there as well. So there is no possibility that your code will continue further. Hence the last return
statement is unreachable.
您的代码有多个返回路径。if
如果满足您的条件,您将从第一个语句返回,else
部分您有try
块。在try
您返回的基础上if
以及else
,因此如果没有发生异常,您可以保证从try
块返回,如果出现异常,您有一个catch
语句并且您也从那里返回。所以你的代码不可能继续下去。因此,最后一条return
语句无法访问。
回答by Adam Arold
Just follow through your code. The last return
statement will never be run because every other branch before that leads to an other return
statement.
只需按照您的代码进行操作。最后一条return
语句永远不会运行,因为在此之前的每个其他分支都会导致另一个return
语句。