此String构造函数JAVA出现问题

问题描述

我正在尝试使用构造函数

public String(byte[] bytes,Charset charset)

详细说明here。 我正在使用它将字节数组转换为ASCII。这是代码

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

不幸的是,这给了我

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

尝试使用其他配置,例如““ String msg = new String(data,0,data.length,” ASCII“);”也不起作用。

这不再是可用的构造函数,还是我做错了什么?

解决方法

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

说明

问题在于您可能正在写new String(raw,"nonsensefoobar"),这显然是毫无意义的。

因此Java迫使您告诉它您打算如何处理这种编码方案不存在的特殊情况。通过 try-catching 或声明 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");
    ...
}

这是一个非常普通和常见的例外情况,我建议了解例外情况


更好的解决方案

您可以使用构造函数的另一种重载,而不是将编码方案指定为字符串,然后再处理异常,该重载采用Java知道它们存在的预定义方案,因此不会因异常而困扰您:

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