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 an occur and I don't know how I should handle those. Suppressing them by doing a simple ´e.printStackTrace()´ doesn't seem like a nice idea so I began reading up on exception-handling best-practices but I still am a bit lost. What should I do with the exceptions?
I need to do something with my exceptions because I don't want to return null
from the method. Returning a null
from my method means that the the calling method will have no insight as to whether an exception happened inside my method.
Should I create a custom exception and raise that or should I simply raise unchecked exceptions?
The calling method can't really do much to affect my method i.e. a SocketException
may occur if there was a problem with the network connectivity, and a IOException
may occur if there was a problem reading the stream. The most that the calling method can do is to retry this at a later time.
If I re-throw all the exceptions that I have trapped, the calling method would simply get riddled with exception-handling blocks.
(I'm sorry if this seems like a trivial question. I'm simply trying to learn to write better code. Thanks.)