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

后端 未结 3 2201
梦毁少年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.

提交回复
热议问题