What is the recommended way to handle an UnsupportedEncodingException when calling String.getBytes("UTF-8") inside a library method?
If I'm reading http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html correctly, UTF-8 encoding should always be available, which leads me to believe there's no reason to pass this exception on to the library's consumer (that is, add a throws
clause to the method signature). It seems any failure mode that made UTF-8 encoding facilities unavailable would be catastrophic, leading 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 wouldn't be addressed by this snippet?
The getBytes() function is an inbuilt method of Java that converts a string into a sequence of bytes. The getBytes() method takes the string which is to be converted and returns the byte array.
The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4. In order to convert a String into UTF-8, we use the getBytes() method in Java. The getBytes() method encodes a String into a sequence of bytes and returns a byte array.
UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String getBytes throws java.
getBytes() This function takes no arguments and used the default charset to encode the string into bytes. getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.
You know what I do?
return "blah".getBytes( Charset.forName( "UTF-8" ) );
This one doesn't throw a checked exception.
Update: Since Java 1.7, we have StandardCharsets.
return "blah".getBytes( StandardCharsets.UTF_8 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With