Is Java UTF-8 Charset exception possible?
It's supposed to be present in every Java runtime, so it is reasonable to re-throw a runtime exception if it is missing. I wouldn't call that "suppressing," though. To me, suppressing means catching the exception and pretending it didn't happen; not sure how you'd proceed if the encoding is missing.
According to the Javadoc for Charset
, every Java implementation must support UTF-8, along with a few other charsets. Therefore, I think you can safely suppress the exception; unless you have a non-compliant Java implementation, this shouldn't be able to fail.
The most simple way is to create a UTF-8 charset constant. Then you don't have to catch the UnsupportedEncodingException again and again:
public class Charsets {
public static final Charset UTF_8 = Charset.forName("UTF-8");
}
Edit (2014-04):
With Java 7 you don't have to create your own constant. You can simply use StandardCharsets.UTF_8
instead.
As McDowell noted in a comment to templatetypdef's answer: If you use a Charset
object when you instantiate a new String
instead of passing the name of the charset, you don't have to deal with an UnsupportedEncodingException
or any other checked exception:
byte[] bytes = ...;
// Requires you to handle UnsupportedEncodingException
String s1 = new String(bytes, "UTF-8");
// Doesn't require you to handle any checked exceptions
String s2 = new String(bytes, Charset.forName("UTF-8"));
It's an inconsistency in Java's standard library that we have to live with...
Note that Charset.forName(...)
can throw exceptions (IllegalCharsetNameException
, IllegalArgumentException
, UnsupportedCharsetException
), but these are all unchecked exceptions, so you don't have to catch or re-throw them yourself.
edit - Since Java 7 there's class java.nio.charset.StandardCharsets
which has constants for frequently used character encodings. Example:
String s3 = new String(bytes, StandardCharsets.UTF_8);