URL decoding: UnsupportedEncodingException in Java

后端 未结 3 694
说谎
说谎 2020-12-08 18:43

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(S

相关标签:
3条回答
  • 2020-12-08 18:48

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

    0 讨论(0)
  • 2020-12-08 18:54

    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");
    }
    
    0 讨论(0)
  • 2020-12-08 19:02

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

    0 讨论(0)
提交回复
热议问题