Recommended UnsupportedEncodingException Handling Method from String.getBytes ("UTF-8")

What is the recommended way to handle UnsupportedEncodingException when calling String.getBytes ("UTF-8") inside the library method?

If I read http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html correctly, UTF-8 encoding should always be available, which makes me believe that there is no reason for pass this exception to the library user (i.e. add a throws to the method signature). It seems that any failure mode due to which UTF-8 encoding tools are not available will be catastrophic, which will lead me to write this handler:

  try { .... return "blah".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // we're assuming UTF-8 encoding is always available. // see // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html e.printStackTrace(); return null; //prevent compile-time "method must return a result" errors } 

Is there a failure mode that will not be fixed by this fragment?

+8
java string character-encoding
source share
2 answers

Do you know what I'm doing?

 return "blah".getBytes( Charset.forName( "UTF-8" ) ); 

This does not throw an exception thrown.

Update . Starting with Java 1.7 StandardCharsets .

 return "blah".getBytes( StandardCharsets.UTF_8 ); 
+35
source share

I came across this question while trying to find out if UTF-8 is available. So thanks for the link.

I agree that there is no need to throw a checked exception when it comes to encoding and decoding using a specific character set that is guaranteed to be available. If the character set was the passed variable, I would probably throw an UnsupportedEncodingException.

This is what I am doing in a similar part of Android code:

 public static String encode(String input) { try { return URLEncoder.encode(input, CharEncoding.UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } 

CharEncoding.UTF_8 is just a String Apache constant for "UTF-8".

Judge The mental proposal to use StandardCharsets.UTF_8 excellent, but for those of us who are developing Android, it is only available on SDK 19 (KitKat) and higher.

+1
source share

All Articles