UnsupportedEncodingException为什么不是RuntimeException的子类?

huangapple go评论132阅读模式
英文:

Why is UnsupportedEncodingException not a subclass of RuntimeException?

问题

我在使用UTF-8编码的情况下遇到了UnsupportedEncodingException,这迫使我编写如下的代码:

String foo = ... // 包含不安全字符
try {
    foo = URLEncoder.encode(foo, "UTF-8");
} catch (UnsupportedEncodingException e) {
    // 处理不应该发生的异常
}

而不是仅仅这样:

String foo = ... // 包含不安全字符
foo = URLEncoder.encode(foo, "UTF-8");

URLEncoder的文档不鼓励使用除UTF-8之外的任何编码方式:

注意:World Wide Web Consortium 建议使用UTF-8。不这样做可能会引入不兼容性。

而根据文档中的支持的编码方式页面,UTF-8编码应该始终可用。

关于如何处理UnsupportedEncodingException以及它是否可能发生的问题的被接受的答案是:“除非您的JVM存在根本性故障,否则不可能发生”。

所以我在想,为什么UnsupportedEncodingException类没有扩展RuntimeException类,这将允许我使用第二个代码段?难道只是因为它存在的方式如现在这样,改变它会很困难吗?

英文:

I've come across the UnsupportedEncodingException while using the URLEncoder with the UTF-8 encoding and it forces me to write my code like this:

String foo = ... // contains unsafe characters
try {
    foo = URLEncoder.encode(foo, "UTF-8");
} catch (UnsupportedEncodingException e)
    // do something with the exception that should never occur
}

Instead of just this:

String foo = ... // contains unsafe characters
foo = URLEncoder.encode(foo, "UTF-8");

The documentation of URLEncoder discourages the use of any encoding other than UTF-8:
> Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilities.

And the UTF-8 encoding should always be available, at least according to the Supported Encodings page from the documentation.

The accepted answer to the question on how to handle the UnsupportedEncodingException and if it can even occur is "It cannot happen, unless there is something fundamentally broken in your JVM".

So I'm wondering, why does the UnsupportedEncodingException class not extend the RuntimeException class, which would allow me to use the second code snippet? Is it just because it exists as it is right now and it would be hard to change that?

答案1

得分: 3

If this was changed some existing code could be broken. For example:

try {
    ... do something that could throw UnsupportedEncodingException
} catch (IOException e) {
    ... handle the exception
}

If UnsupportedEncodingException is no longer an IOException it would not be handled any more.

英文:

If this was changed some existing code could be broken. For example

try {
    ... do something that could throw UnsupportedEncodingException
} catch (IOException e) {
    ... handle the exception
}

If UnsupportedEncodingException is no longer an IOException it would not be handled any more.

huangapple
  • 本文由 发表于 2020年8月11日 00:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63344587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定