简体   繁体   中英

Problem with this String constructor (JAVA)

I am trying to use the constructor

public String(byte[] bytes,
              Charset charset)

Which is detailed here . I'm using it to convert an array of bytes to ASCII. Here is the code

String msg = new String(raw, "US-ASCII");

Unfortunately, this gives me:

error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
    String msg = new String(raw, "US-ASCII");
                 ^

Trying a different configuration like "String msg = new String(data, 0, data.length, "ASCII");" Dosen't work either.

Is this no longer a usable constructor, or am I doing something wrong?

byte[] raw = new byte[]{};
String msg = new String(raw, StandardCharsets.US_ASCII);

Explanation

The problem is that you could be writing new String(raw, "nonsensefoobar") which obviously is non-sense.

Hence Java forces you to tell it how you want to deal with the exceptional case that this encoding scheme does not exist. Either by try-catching it or by declaring throws :

public void myMethod(){
    ...
    try {
        String msg = new String(raw, "US-ASCII");
    ...
    } catch (UnsupportedEncodingException e) {
        ... // handle the issue
    }
    ...
}

// or

public void myMethod() throws UnsupportedEncodingException {
    ...
    String msg = new String(raw, "US-ASCII");
    ...
}

That is a super ordinary and common exception-situation, I would suggest to learn about exceptions .


Better solution

Instead of specifying the encoding scheme as string and then dealing with exceptions, you can use another overload of the constructor which takes in predefined schemes for which Java knows that they exist, so it will not bother you with exceptions:

String msg = new String(raw, StandardCharsets.US_ASCII);

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