简体   繁体   中英

Is Java UTF-8 Charset exception possible?

使用"UTF-8"编码时,Java 是否可能抛出UnsupportedEncodingException ,或者我可以安全地抑制它的抛出?

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);

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.

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.

It depends what you mean by "safe" and "suppress".

I'd be tempted to catch the exception and throw an unchecked exception (or AssertionError ) in its place. The chances are that your application will never experience this. But who knows ... someone might run it on some non-conformant platform in which UTF-8 was not available. And it costs almost nothing to do this ... especially since you have to "do something" with the original exception.

i Have used the below line of code and it worked for me

Old code

byte[] hash = digest.digest(input.getBytes("UFT-8"));

Updated Code

byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM