I have a small method that looks like this:
public static void unstarTrack(Context ctxContext, String strId) { try { HttpParams htpParameters = new BasicHttpParams(); List<NameValuePair> lstCredentials = new ArrayList<NameValuePair>(); lstCredentials.add(new BasicNameValuePair("t", String.valueOf(System.currentTimeMillis() / 1000))); lstCredentials.add(new BasicNameValuePair("__call", "favourites.removeSong")); HttpPost htpPost = new HttpPost(API_URL); htpPost.setEntity(new UrlEncodedFormEntity(lstCredentials)); htpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0"); htpPost.addHeader("Accept-Encoding", "gzip"); DefaultHttpClient dhcClient = new DefaultHttpClient(htpParameters); HttpResponse resResponse = dhcClient.execute(htpPost); Log.d(TAG, EntityUtils.toString(resResponse.getEntity())); return; } catch (SocketException e) { throw new RuntimeException("problem with network connectivity.", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding not supported.", e); } catch (ClientProtocolException e) { throw new RuntimeException("A protocol exception was encountered.", e); } catch (ParseException e) { throw new RuntimeException("An error occurred while trying to read the header elements.", e); } catch (IOException e) { throw new RuntimeException("An error occurred while trying to read response stream.", e); }
}
The method itself is quite simple, but it has a bunch of exceptions that arise, and I don't know how I should handle them. Suppressing them by doing a simple "e.printStackTrace ()" doesn't seem like a good idea, so I started reading the guidelines for handling exceptions, but I'm still a bit lost. What to do with exceptions?
I need to do something with my exceptions because I do not want to return null from the method. Returning null from my method means that the calling method will have no idea if an exception has occurred inside my method.
Should I create a custom exception and raise it, or should I just delete the excluded exceptions?
The calling method cannot really strongly affect my method, i.e. A SocketException problem may occur if there is a problem with the network connection, and an IOException may occur if there is a problem with reading the stream. The most that the calling method can do is repeat this later.
If I throw all the exceptions that I caught, the calling method will simply be riddled with exception handling blocks.
(Sorry if this seems like a trivial question. I'm just trying to learn how to write better code. Thanks.)