Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended method for handling UnsupportedEncodingException from String.getBytes("UTF-8")

Tags:

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?

like image 332
cqcallaw Avatar asked May 25 '12 04:05

cqcallaw


People also ask

What is the purpose of the getBytes () method?

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.

What is getBytes UTF-8?

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.

How do I get UnsupportedEncodingException?

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.

What is string getBytes?

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.


1 Answers

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 );
like image 128
Judge Mental Avatar answered Sep 22 '22 08:09

Judge Mental