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
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.
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.
https://projectlombok.org/features/SneakyThrows
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 );