Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CharacterCodingException — encoding and decoding errors

CharacterCodingException is a checked exception in java.nio.charset that extends IOException. It signals a failure when converting between characters and bytes and provides a common catch type for malformed input and unmappable characters.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public class CharacterCodingException extends IOException
public CharacterCodingException()

CharacterCodingException in java.nio.charset is a checked exception extending IOException. It concerns encoding characters into bytes and decoding bytes into characters. When a called method declares this exception, catch it or declare an appropriate type in throws. The class provides the public no-argument constructor CharacterCodingException().

Its direct subclasses are MalformedInputException and UnmappableCharacterException. The first means an invalid input sequence, such as malformed UTF-8 bytes; the second means a valid sequence that cannot be mapped to the target representation. catch (CharacterCodingException e) catches both kinds of failure. Do not confuse them with UnsupportedCharsetException, which means the requested charset is not supported.

A new CharsetDecoder reports both error types by default; the example explicitly sets CodingErrorAction.REPORT. The one-argument decode(ByteBuffer) then throws the appropriate exception subclass. In contrast, the streaming overload decode(ByteBuffer, CharBuffer, boolean) returns a CoderResult that must be checked. The REPLACE and IGNORE settings replace or discard erroneous input respectively, so they change error handling and can lose information.

Examples

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        var decoder = StandardCharsets.UTF_8.newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT);
        byte[] bytes = {(byte) 0xC3, (byte) 0x28};

        try {
            decoder.decode(ByteBuffer.wrap(bytes));
            System.out.println("Decoded successfully");
        } catch (CharacterCodingException e) {
            System.out.println(e.getClass().getSimpleName());
        }
    }
}

Result

MalformedInputException

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources