简体   繁体   中英

UnsupportedEncodingException is never thrown

So I am trying to use getBytes from a string, and I've read that if it hits a character it can't turn into real data, it'll throw an UnsupportedEncodingException. I added the java.io to provide the exception, but when I put it in a try catch statement, I get, "Unreachable catch block for UnsupportedEncodingException. This exception is never thrown from the try statement body"

Here's my exact construction. myCharacterData is provided by an external program, and it's just a string, but it is very possible that string could hold junk data (since I have no control over what is put into it).

byte[] bytes = {0x40};
try {
    bytes = myCharacterData.getBytes();
} catch (UnsupportedEncodingException saveError) {};

Am I wrong? Can that exception not be thrown? What's the correct exception to be using here?

You are misunderstanding the origin of UnsupportedEncodingException .

It is thrown by methods which take the name of a charset as a String. For example, String.getBytes(String) throws the exception.

The reason it is thrown is if the JVM does not know which charset the name refers to. For example, if you called "".getBytes("flibbly bibbly") , the exception would (almost certainly) be thrown, because that's not the name of a known charset.

Notice that this has nothing to do with the content of the string. For better or for worse (I say for worse), Java does not throw exceptions when encoding or decoding characters to/from bytes.

For example, "🍕" cannot be represented in ISO-8859-1; but you can ask for its bytes, and you get [63] , ie the same as "?" .

Similarly [0xff] is not a valid byte sequence in UTF-8, but new String(new byte[]{(byte)0xff}, "UTF-8") produces " " . In neither case is an exception thrown.

( Ideone demo )

No exception is declared as being thrown either by String.getBytes() , or by String.getBytes(Charset) . This is because you already have a Charset instance before calling these:

  • In the former case, because it uses the JVM default charset - if this doesn't exist, the JVM wouldn't be able to start!
  • In the latter case. Because you've already obtained the charset, eg from Charset.forName(String) . That method throws the exception; but once you've got the result from that, there is no need to "look up" the charset again, so there is no possibility that it becomes "unknown".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM