URL解码:Java中的UnsupportedEncodingException [英] URL decoding: UnsupportedEncodingException in Java

查看:151
本文介绍了URL解码:Java中的UnsupportedEncodingException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文档中了解到, UnsupportedEncodingException 只能指定一个错误的编码作为URLDecoder.decode(String,String)方法的第二个参数。是这样吗?我需要知道可以抛出这个异常的情况。

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?
    }
}

由于我明确提到UTF-8有什么办法可以抛出这个异常吗?我需要在catch块中做任何事情吗?或者,如果我的理解是完全错误的,请让我知道。

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.

推荐答案

不可能发生,除非有根本的破坏你的JVM但是我认为你应该写成:

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!!");'
}

这样做的代价是永远不会执行的几个字节的代码,一个永远不会被执行的字符串用过的。那个小的价格是为了保护你可能误读/误解了javadocs(你没有在这种情况下)...或者规范可能会改变的可能性(在这种情况下不会)...

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

这篇关于URL解码:Java中的UnsupportedEncodingException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆