从String.getBytes(“UTF-8”)处理UnsupportedEncodingException的推荐方法 [英] Recommended method for handling UnsupportedEncodingException from String.getBytes("UTF-8")
问题描述
在调用时,处理 UnsupportedEncodingException 的建议方法是什么? String.getBytes(UTF-8)里面的库方法?
What is the recommended way to handle an UnsupportedEncodingException when calling String.getBytes("UTF-8") inside a library method?
如果我正在阅读 http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html ,UTF-8编码应始终 这使我相信没有理由将此异常传递给库的消费者(即,在方法签名中添加一个 throws
子句)。似乎任何使UTF-8编码设施不可用的失败模式将是灾难性的,导致我写这个处理程序:
If I'm reading http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html correctly, UTF-8 encoding should always be available, which leads me to believe there's no reason to pass this exception on to the library's consumer (that is, add a throws
clause to the method signature). It seems any failure mode that made UTF-8 encoding facilities unavailable would be catastrophic, leading me to write this handler:
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
}
推荐答案
你知道我在做什么吗?
return "blah".getBytes( Charset.forName( "UTF-8" ) );
这不会引发检查异常。
更新:自Java 1.7开始,我们有 StandardCharsets 。
Update: Since Java 1.7, we have StandardCharsets.
return "blah".getBytes( StandardCharsets.UTF_8 );
这篇关于从String.getBytes(“UTF-8”)处理UnsupportedEncodingException的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!