0

Whenever i am trying to encode or decode a string using UTF - 8 it is showing me Unhandled Exception: UnsupportedEncodingException.

So Android Studio is giving me two solution, which are

1) Use throws UnsupportedEncodingException 2) put that piece of code between try catch with UnsupportedEncodingException as catch argument..

So which one is good practice to use and why ?

 public static String getEncodedString(String strOriginal) throws UnsupportedEncodingException {
    byte[] dataFirstName = strOriginal.getBytes("UTF-8");
    return Base64.encodeToString(dataFirstName, Base64.DEFAULT);
}

OR

  public static String getEncodedString(String strOriginal)  {
    byte[] dataFirstName = new byte[0];
    try {
        dataFirstName = strOriginal.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return Base64.encodeToString(dataFirstName, Base64.DEFAULT);
}
Niki
  • 1,566
  • 1
  • 19
  • 36

1 Answers1

1

I would go for the second snippet, UTF-8 is one of the standard character encodings supported by every platform so the exception can actually never happen. It does not make sense to propagate it further.

If you are developing for API 19 or later, you can also use

strOriginal.getBytes(StandardCharsets.UTF_8)

which does not throw an exception.

Henry
  • 42,982
  • 7
  • 68
  • 84
  • Ohh okay.. thanks a bunch.. and one more query can you check before decoding a string , is given string is encoded by StandardCharsets.UTF_8 or not ? – Niki Jun 16 '17 at 12:07
  • No, in general you don't see the encoding used by a given sequence of bytes. This is something you have to know. – Henry Jun 16 '17 at 12:23
  • No i am newbie in this. and i didn't know that. I thought there has to be some class or something using which i can identify if the string is encoded or not.. cz in my old data there were no encoding present, and now i have to encode and decode it.. so whenever i try to decode the string which is not encoded which is old data, it crashes the app.. so i am trying to figure it out.. Thanks for reply though :) – Niki Jun 16 '17 at 12:28
  • Sorry, you misunderstood me. I meant you have to know the encoding in advance because you can't determine it from the encoded bytes. – Henry Jun 16 '17 at 13:17