1

I am trying transform a string to UTF-8 encoding. But the compilation fails because some code "throws UnsupportedEncodingException".

String s = "1,2,3,4";
String smsext = new String(s.getBytes(),"UTF-8");

how to solve this ?

ben75
  • 29,217
  • 10
  • 88
  • 134
wky
  • 23
  • 2

2 Answers2

3

The exception UnsupportedEncodingException is thrown by the String constructor (not by Android Studio !!!). This is a checked exception and so your code must handle it in some way.

In this particular case : the exception will never be thrown because "UTF-8" is hardcoded and always supported by any JVM (this is a requirement). So you can catch it silently :

String s = "1,2,3,4";
String smsext = null;
try{
    smsext = new String(s.getBytes(),"UTF-8");
}catch(UnsupportedEncodingException e){
    //can never occurs
}

But I don't recommend this over simplistic approach because silently catching an exception is almost always a very bad practice. A more appropriate solution for catched exception that never append is to rethrow the exception encapsulated in an unchecked exception :

String s = "1,2,3,4";
String smsext = null;
try{
    smsext = new String(s.getBytes(),"UTF-8");
}catch(UnsupportedEncodingException e){
    //can never occurs because UTF-8 is always supported
    throw new RuntimeException(e);
}

With this code, if one day you change the body of the try-catch block so that UnsupportedEncodingException can possibly occurs : the exception won't be ignored silently.

ben75
  • 29,217
  • 10
  • 88
  • 134
  • right,I forget try{}catch{},so that throws this UnsupportedEncodingException.thank you. – wky Nov 09 '14 at 10:50
0

try to use the String constructor with the charset paramete (with try{}catch{}), take a look at this answer

Community
  • 1
  • 1
Rami
  • 7,879
  • 12
  • 36
  • 66