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

后端 未结 3 2194
梦毁少年i
梦毁少年i 2021-02-12 13:10

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

相关标签:
3条回答
  • 2021-02-12 13:41

    I ran across this question while trying to figure out if UTF-8 is always 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 a variable that was passed in, I would probably throw UnsupportedEncodingException.

    This is what I am doing in a similar piece 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 Apache Commons' String constant for "UTF-8".

    Judge Mental's suggestion to use StandardCharsets.UTF_8 is great but for those of us doing Android development, it's only available on SDK 19 (KitKat) and above.

    0 讨论(0)
  • 2021-02-12 13:44

    If you use Lombok, @SneakyThrows annotation can be used to avoid this.

    From Lombok documentation:

    "@SneakyThrows can be used to sneakily throw checked exceptions without actually declaring this in your method's throws clause.

    • An 'impossible' exception. For example, new String(someByteArray, "UTF-8"); declares that it can throw an UnsupportedEncodingException but according to the JVM specification, UTF-8 must always be available. An UnsupportedEncodingException here is about as likely as a ClassNotFoundError when you use a String object, and you don't catch those either! "

    https://projectlombok.org/features/SneakyThrows

    0 讨论(0)
  • 2021-02-12 13:49

    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 );
    
    0 讨论(0)
提交回复
热议问题