cqc*_*law 17 java string character-encoding
在库方法中调用String.getBytes("UTF-8")时,处理UnsupportedEncodingException的推荐方法是什么?
如果我正确地阅读http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html,UTF-8编码应始终可用,这让我相信没有将此异常传递给库的使用者的原因(即,throws在方法签名中添加一个子句).似乎任何使UTF-8编码工具不可用的故障模式都是灾难性的,导致我编写这个处理程序:
try
{
....
return "blah".getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
// we're assuming UTF-8 encoding is always available.
// see
// http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
e.printStackTrace();
return null; //prevent compile-time "method must return a result" errors
}
Run Code Online (Sandbox Code Playgroud)
是否存在此代码段无法解决的故障模式?
Jud*_*tal 49
你知道我在做什么吗?
return "blah".getBytes( Charset.forName( "UTF-8" ) );
Run Code Online (Sandbox Code Playgroud)
这个不会抛出一个检查过的异常.
更新:自Java 1.7以来,我们有StandardCharsets.
return "blah".getBytes( StandardCharsets.UTF_8 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14716 次 |
| 最近记录: |