0

If I were to encode a string using the encode method of the URLEncoder class, when will it throw the UnsupportedEncodingException?

String encodedString = URLEncoder.encode(myString, "UTF-8");

I have read the documentation which reads,

Throws: UnsupportedEncodingException - If the named encoding is not supported

So, will this ever happen to my code if I always use "UTF-8"?

11
  • what is the value of myString ? Commented Jan 27, 2018 at 6:38
  • Well, thats what I want to know. Will it get thrown if I give any specific value to the string? Commented Jan 27, 2018 at 6:39
  • My question is what is the value of that value ?? Commented Jan 27, 2018 at 6:40
  • 2
    It won't happen if you use any of the standard encodings. It's just there in case you specify "XYZ". Commented Jan 27, 2018 at 6:44
  • 1
    There are no 'unencodable' strings, if a character does not exist in the target character set, it is replaced with either a ? or the unicode replacement character (or U+FFFD). Commented Jan 28, 2018 at 12:31

1 Answer 1

2

You should be fine with UTF-8, it depends on JVM installed on computer, where final application will run. Anyhow UTF-8 is now supported by java.

You can use static constants in StandardCharsets class:

URLEncoder.encode("Your string", StandardCharsets.UTF_8.toString());

Sign up to request clarification or add additional context in comments.

2 Comments

Lets say, with the latest JVM. Java(TM) SE Runtime Environment (build 1.8.0_151-b12) :)
As far as you use StandardCharsets constants you are covered. Exception is thrown when you use different encodings. With UTF-8. You can check it here in doc link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.