Recommended method for handling UnsupportedEncodingException from String.getBytes(“UTF-8”)

后端 未结 3 2234
梦毁少年i
梦毁少年i 2021-02-12 13:10

What is the recommended way to handle an UnsupportedEncodingException when calling String.getBytes(\"UTF-8\") inside a library method?

If I\'m reading http://docs.orac

3条回答
  •  我在风中等你
    2021-02-12 13:49

    You know what I do?

    return "blah".getBytes( Charset.forName( "UTF-8" ) );
    

    This one doesn't throw a checked exception.

    Update: Since Java 1.7, we have StandardCharsets.

    return "blah".getBytes( StandardCharsets.UTF_8 );
    

提交回复
热议问题