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

查看:18
本文介绍了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天全站免登陆