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

后端 未结 3 2195
梦毁少年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:44

    If you use Lombok, @SneakyThrows annotation can be used to avoid this.

    From Lombok documentation:

    "@SneakyThrows can be used to sneakily throw checked exceptions without actually declaring this in your method's throws clause.

    • An 'impossible' exception. For example, new String(someByteArray, "UTF-8"); declares that it can throw an UnsupportedEncodingException but according to the JVM specification, UTF-8 must always be available. An UnsupportedEncodingException here is about as likely as a ClassNotFoundError when you use a String object, and you don't catch those either! "

    https://projectlombok.org/features/SneakyThrows

提交回复
热议问题