java.io.UnsupportedEncodingException in Java with Examples
The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String getBytes throws java.io.UnsupportedEncodingException with the encoding format given.
The character encoding is used to determine how the raw binary is to be interpreted to a character. The default encoding for English Windows systems in CP1252. Other languages and systems can use a different default encoding. The UTF-8 encoding scheme is generally used as a character encoding scheme. In java, String.getBytes() and StringCoding.encode() methods are used to interpret between raw bytes and java strings.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.io.UnsupportedEncodingException
Remember: It does implement Serializable interfaces.
Syntax:public class UnsupportedEncodingException extends IOException
The Character Encoding is not supported. Further moving ahead let us do go through the constructors of this class which are s follows:
- UnsupportedEncodingException(): Constructs an UnsupportedEncodingException without a detail message.
- UnsupportedEncodingException(String s): Constructs an UnsupportedEncodingException with a detailed message.
Now let us find a way out in order to how to reproduce this issue as stated UnsupportedEncodingException in java. We will carry over with the help of an example provided below that will be throw java.io.UnsupportedEncodingException. The “UTF” encoding scheme is an invalid encoding scheme name. It is because java can not interpret the string to bytes if the encoding scheme is unknown or not supported. Java will throw java.io. UnsupportedEncodingException if an unknown or unsupported encoding method is identified.
Now we are well versed with the exception and have discussed why does it occur. Now let us figure a way out to get rid iff from this exception by proposing the solution to it. The java supported encoding scheme name should be provided in String.getBytes method. Do go through the set of provided methods been up here before proceeding further.
Hence, the CharsetEncoder class should be used when more control over the encoding process is required. The String.getBytes method returns with an array of bytes.
Given String : GeeksforGeeks Output bytes : [B@7cc355be