Reputation: 2003
I have had a lot of fun using Gson from Google to parse Json this afternoon, but I was writing this code here:
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. I didn't think I would have to ask for this. Ideas please.
Upvotes: 1
Views: 390
Reputation: 6556
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.
if (jReader!=null) {
//do something
}
Note: an explicit return null; is not a good programing practice, nor two return statements.
Upvotes: 1
Reputation: 459
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.
You should return null;
or something that you want to return in case the try fails.
Upvotes: 1
Reputation: 10172
If you want to catch exceptions (sure you want?) then return null
could be the right choice.
Upvotes: 2