[英]java try catch block what to return
I have had a lot of fun using Gson from Google to parse Json this afternoon, but I was writing this code here: 今天下午,我使用Google的Gson解析Json感到很开心,但是我在这里编写了以下代码:
public class Fetcher extends AsyncTask<String, Void, JsonReader> {
@Override
protected JsonReader doInBackground(String... urlString) {
try {
URL url = new URL(urlString[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
JsonReader jReader = new JsonReader(reader);
return jReader;
} catch(MalformedURLException malformedEx) {
Log.e("malformed url: ", "here are the details: ", malformedEx);
} catch(IOException ioEx) {
Log.e("IO problem: ", "here are the details: ", ioEx);
} catch(Exception generalEx) {
Log.e("an exception we did not expect: ", "here are the details: ", generalEx);
}
//return statement here
}
}
It is obviously going to complain that I am missing a return statement, but I am not sure what to return since I need to put the JsonReader in the try block and I can't just create an empty one since there is no constructor for it. 很显然,我会抱怨我缺少一个return语句,但是我不确定要返回什么,因为我需要将JsonReader放在try块中,而且由于没有构造函数,所以我不能只创建一个空语句。 I didn't think I would have to ask for this.
我认为我不必要求这个。 Ideas please.
请点子。
如果要捕获异常(确定要捕获?),则return null
可能是正确的选择。
Since the method needs to return something and the try/catch can fail, you need to return something in the case of not being able to reach the return statement in the try/catch . 由于该方法需要返回某些内容,并且try / catch可能失败,因此, 在无法到达try / catch中的return语句的情况下 , 您需要返回某些内容 。
You should return null;
您应该
return null;
or something that you want to return in case the try fails. 或您想要返回的内容,以防尝试失败。
I think the best option should be 我认为最好的选择应该是
public class Fetcher extends AsyncTask<String, Void, JsonReader> {
@Override
protected JsonReader doInBackground(String... urlString) {
JsonReader jReader = null;
try {
URL url = new URL(urlString[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
jReader = new JsonReader(reader);
} catch(MalformedURLException malformedEx) {
Log.e("malformed url: ", "here are the details: ", malformedEx);
} catch(IOException ioEx) {
Log.e("IO problem: ", "here are the details: ", ioEx);
} catch(Exception generalEx) {
Log.e("an exception we did not expect: ", "here are the details: ", generalEx);
} finally {
// CLOSE YOUR STREAMS
}
return jReader;
}
}
But don't forget to test jreader before you use it or you can get a null pointer exception. 但是,请不要忘记在使用jreader之前对其进行测试,否则可能会得到null指针异常。
if (jReader!=null) {
//do something
}
Note: an explicit return null; 注意:显式传回null; is not a good programing practice, nor two return statements.
这不是好的编程习惯,也不是两个return语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.