Search code examples
androidencodingutf-8exceptiondecoding

Which solution to use at the time of encoding string using UTF - 8 in android?


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);
}

Solution

  • 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.