英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论