问题描述
我在使用UnsupportedEncodingException
和UTF-8编码时遇到了URLEncoder
,这迫使我编写这样的代码:
String foo = ... // contains unsafe characters
try {
foo = URLEncoder.encode(foo,"UTF-8");
} catch (UnsupportedEncodingException e)
// do something with the exception that should never occur
}
不仅仅是这个:
String foo = ... // contains unsafe characters
foo = URLEncoder.encode(foo,"UTF-8");
documentation of URLEncoder
不鼓励使用UTF-8以外的任何其他编码方式:
注:万维网联盟建议书指出应使用UTF-8。不这样做可能会导致不兼容。
至少应根据文档中的Supported Encodings页,并且应始终使用UTF-8编码。
关于how to handle the UnsupportedEncodingException
上的问题(甚至可能发生)的公认答案是“除非在您的JVM中有根本性的中断,否则它不会发生”。
所以我想知道,为什么UnsupportedEncodingException类不扩展RuntimeException类,这将允许我使用第二个代码段?仅仅是因为它现在就存在并且很难改变它吗?
解决方法
如果对此进行了更改,则可能会破坏某些现有代码。例如
try {
... do something that could throw UnsupportedEncodingException
} catch (IOException e) {
... handle the exception
}
如果UnsupportedEncodingException
不再是IOException
,将不再处理。