URL decoding: UnsupportedEncodingException in Java

JavaEncoding

Java Problem Overview


What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

Java Solutions


Solution 1 - Java

It cannot happen, unless there is something fundamentally broken in your JVM. But I think you should write this as:

try {
    value = URLDecoder.decode(keyVal[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new AssertionError("UTF-8 is unknown");
    // or 'throw new AssertionError("Impossible things are happening today. " +
    //                              "Consider buying a lottery ticket!!");'
}

The cost of doing this is a few bytes of code that will "never" be executed, and one String literal that will never be used. That a small price for the protecting against the possibility that you may have misread / misunderstood the javadocs (you haven't in this case ...) or that the specs might change (they won't in this case ...)

Solution 2 - Java

That's because of the odd choice to make UnsupportedEncodingException checked. No, it won't be thrown.

I usually do as follows:

} catch (UnsupportedEncodingException e) {
  throw new AssertionError("UTF-8 not supported");
}

Solution 3 - Java

In your special case - no, it won't be thrown. Unless you execute your code in a Java runtime that does not support "UTF-8".

Solution 4 - Java

To answer an old question for newer readers:

Java 11 now has URLDecoder.decode(String, Charset); which does not throw. So you don't have to use a try-catch block at all. Just do:

URLDecoder.decode(keyVal[1], StandardCharsets.UTF_8);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHari MenonView Question on Stackoverflow
Solution 1 - JavaStephen CView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaAndreas DolkView Answer on Stackoverflow
Solution 4 - Javak314159View Answer on Stackoverflow