4

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.)

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
  • 1
    You're throwing an exception for caught exception; if an exception happens, you won't be returning null, you won't be returning anything. Your method is declared as `void` anyway--you *can't* return anything. *How* to handle the exception depends entirely on... how you want to handle the exceptions. – Dave Newton Jan 21 '13 at 20:44
  • Only catch exceptions that makes a difference to the user or yourself. An exception has a getMessage() method that can be used in any case, even if it was catched with catch(Exception e). Also decide what to happen if any of those exceptions occur. Should the application terminate? Should it show a message? Only catch specialized exceptions if you come up with a different answer for some exception. – Anders Lindén Jan 21 '13 at 21:09

1 Answers1

2

Create a dedicated exception, which has the appropriate abstraction level (something like UnstarTrackException). Throw such an exception, wrapping the original exception you caught. That way, the caller will only have to handle one exception (I assume all the exceptions should be handled the same way: retrying).

Whether this exception should be checked or not depends on your taste. If you want to force all the callers of your method to handle this exception, make it a checked exception. If you want to let the caller choose whether he wants to handle this exception or not, use a runtime exception.

If this method is buried deep inside layers of code, and if an exception can only be handled at the top layer, a runtime exception is probably a better choice. And in fact, unless you're the only caller of this method, a runtime exception is also probably a better choice. Checked exceptions tend not to be used much nowadays.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • "Checked exceptions tend not to be used much nowadays." Really? Evidence? – user207421 Nov 12 '13 at 00:06
  • Hibernate went from checked to all unchecked exceptions. JDBC uses checked exceptions, but JPA only uses runtime ones. Spring uses (almost?) only runtime exceptions. The Java 8 `java.time` API has only runtime exceptions (like DateTimeParseException) although the old SimpleDateFormat class uses a checked ParseException. See also http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html – JB Nizet Nov 12 '13 at 09:20