Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.regex.PatternSyntaxException: practical reference

util.regex.PatternSyntaxException: practical reference: PatternSyntaxException is an unchecked IllegalArgumentException that reports a syntax error while a regular-expression pattern is compiled.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.regex.PatternSyntaxException

PatternSyntaxException is an unchecked IllegalArgumentException that reports a syntax error while a regular-expression pattern is compiled.

Catch it at a configuration or regex-editor boundary to display getDescription, getPattern, and the position from getIndex.

Do not treat it as an input mismatch: a malformed pattern causes the exception, whereas ordinary non-matching returns false.

getIndex may return -1 when the position is unknown, and getMessage builds a multi-line diagnostic with the pattern and error indicator.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        try { java.util.regex.Pattern.compile("["); } catch (java.util.regex.PatternSyntaxException error) { System.out.println(error.getIndex()); }
    }
}

Result

0

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources