CKTIS / Java
CodingErrorAction: reporting and replacing invalid input
CodingErrorAction controls how a charset decoder or encoder handles coding errors. REPORT exposes an error to the caller, while REPLACE substitutes the configured replacement and continues processing. Malformed input and unmappable characters have independently configured policies.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
coder.onMalformedInput(CodingErrorAction.REPORT);
coder.onUnmappableCharacter(CodingErrorAction.REPLACE);CodingErrorAction in java.nio.charset defines error-handling policies for CharsetDecoder and CharsetEncoder. It is a class with constants representing available actions, not an enum declaration. Malformed input violates the encoding rules; an unmappable error means a valid sequence cannot be represented in the output. Configure these policies independently through onMalformedInput(...) and onUnmappableCharacter(...).
CodingErrorAction.REPORT reports an error: incremental buffer-processing methods return an appropriate CoderResult, whereas the single-argument decode(...) and encode(...) methods throw an appropriate subclass of CharacterCodingException. New decoders and encoders default to REPORT for both error categories. This does not mean every text-conversion API uses the same policy.
CodingErrorAction.REPLACE skips the erroneous input, appends the replacement value, and continues. A decoder inserts text; an encoder inserts bytes. Change that value with replaceWith(...). This loses information rather than repairing the original. Choose REPORT when errors must be detected, and REPLACE only when substitution is acceptable. The Java SE 21 example compares both actions on an invalid UTF-8 byte and explicitly sets ? to make the output readable.
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) throws CharacterCodingException {
byte[] input = {(byte) 0xFF, 0x41};
var strict = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT);
try {
strict.decode(ByteBuffer.wrap(input));
} catch (CharacterCodingException e) {
System.out.println("REPORT: " + e.getClass().getSimpleName());
}
var tolerant = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.replaceWith("?");
System.out.println("REPLACE: " + tolerant.decode(ByteBuffer.wrap(input)));
}
}Result
REPORT: MalformedInputException REPLACE: ?A
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.