0

I have to set private InputStream responseMsg in my struts 2 application action class methods using following code

responseMsg = new ByteArrayInputStream(message.getBytes("UTF-8"));

in this case i have to handle UnsupportedEncodingException checked exception. I want to assign InputStream in so many action methods if i added throws UnsupportedEncodingException in all methods means code looks messy. so i decided to create utility method in a Utility class

public class Utilities {

    public InputStream responseMessage(String message) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(message.getBytes("UTF-8"));
    }
}

invoked from my action class

responseMsg = new Utilities().responseMessage(message);

in this case also compile time error coming to handle UnsupportedEncodingException in action methods, help me to create Utility methods for all of my action class methods.

rpandidurai
  • 307
  • 1
  • 5
  • 13
  • just handle the exception.... don't understand what you are asking. – T McKeown Jul 28 '14 at 16:22
  • What are you saving with the Utility method? It would still throw UnsupportedEncodingException, and the callers of that method would have to handle it or declare that they throw it. – Eran Jul 28 '14 at 16:24

1 Answers1

1

If you are talking about "UTF-8" specifically, the recommended way is to throw an Error if something that must work by specification doesn’t. E.g.

public InputStream responseMessage(String message) {
  try {
    return new ByteArrayInputStream(message.getBytes("UTF-8"));
  } catch(UnsupportedEncodingException ex) {
    throw new AssertionError("Every JVM must support UTF-8", ex);
  }
}

Since Java 7 live is much easier for this specific case:

public InputStream responseMessage(String message) {
  return new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
}

If it comes to arbitrary charsets, you should handle the possible exception, which is not a big deal as your code using the returned InputStream will have to deal with the declared IOExceptions anyway and UnsupportedEncodingException is a subclass of IOException. So the required catch or throws clause for IOException will cover UnsupportedEncodingException already.

Holger
  • 285,553
  • 42
  • 434
  • 765