I'm writing an Android application that is connecting to a website and retrieving search results in the form of JSON. This function is happening in an AsyncTask, which is set up as a separate stream from the UI. I need to handle the case where the connection is interrupted/non-existent/too latent. I need to handle this case in order to display an AlertDialog to the user letting them know the connection is bad. I don't know if there is an exception I should be trying to catch, or if I should throw my own. I've seen posts suggest setting a timeout parameter for URLConnection, but I'm not using URLConnection right now.
Right now, when I run the emulator and disable my PC's internet connection, running the function brings up a "Force Close" message and produces an UnknownHostException. I can't explicitly catch this exception - it won't compile in my editor, telling me that IOException in the below code covers that already.
I also need to handle a case where no thumbnail can be found, which produces a FileNotFoundException. Trying to catch this exception with the other catch statements will prevent my application from compiling.
Please advise me on what I should do. Thanks.
@Override protected HashMap<String, String> doInBackground(Object... params) { InputStream imageInput = null; FileOutputStream imageOutput = null; try { URL url = new URL("http://www.samplewebsite.com/" + mProductID); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String jsonOutput = ""; String temp = ""; while ((temp = reader.readLine()) != null) { jsonOutput += temp; } JSONObject json = new JSONObject(jsonOutput); // ... Do some JSON parsing and save values to HashMap String filename = mProductID + "-thumbnail.jpg"; URL thumbnailURL = new URL("http://www.samplewebsite.com/img/" + mProductID + ".jpg"); imageInput = thumbnailURL.openConnection().getInputStream(); imageOutput = mContext.openFileOutput(outputName, Context.MODE_PRIVATE); int read; byte[] data = new byte[1024]; while ((read = imageInput.read(data)) != -1) { imageOutput.write(data, 0, read); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { try { imageOutput.close(); imageInput.close(); } catch (IOException e) { e.printStackTrace(); } } return mProductInfoHashMap; }