[英]Problem with this String constructor (JAVA)
我正在嘗試使用構造函數
public String(byte[] bytes,
Charset charset)
此處詳細介紹。 我正在使用它將字節數組轉換為 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 迫使你告訴它你想如何處理這種編碼方案不存在的例外情況。 通過嘗試捕獲它或通過聲明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");
...
}
這是一個超級普通和常見的異常情況,我建議學習 exceptions 。
除了將編碼方案指定為字符串然后處理異常,您可以使用構造函數的另一個重載,它接受 Java 知道它們存在的預定義方案,因此它不會因異常而困擾您:
String msg = new String(raw, StandardCharsets.US_ASCII);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.