Skip to content
Related Articles

Related Articles

PatternSyntaxException Class in Java

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 16 Feb, 2022

Java uses the java.util.regex API for pattern matching with Regular expressions. To indicate any syntax errors in a regular-expression pattern, Java provides a class called PatternSyntaxException.

PatternSyntaxException Class in Java:

While writing regular expressions, to identify and throw any syntactical errors in the pattern, PatternSyntaxException class is used. This is an unchecked exception available in java.util.regex package from java 1.4 version.

Syntax:

public class PatternSyntaxException extends IllegalArgumentException implements Serializable

Hierarchy of PatternSyntaxException class:

Hierarchy of PatternSyntaxException class

The constructor of PatternSyntaxException Class:

To construct a new instance of the PatternSyntaxException class.

Syntax:

PatternSyntaxException(String desc, String regex, int index)

Parameters:

  • desc: Description of the error.
  • regex: The pattern which is incorrect.
  • index: The approximate index of the error in the regex pattern, or -1 if the index is not known.

Methods in PatternSyntaxException Class

S. No. Method Name Modifier Description
1 getIndex() int It returns the approximate index of the error in the pattern, or -1 if the index is not known.
2 getDescription() String It returns the description of the error in the pattern.
3 getMessage() String It returns the description of the syntax error in the pattern and its index, the incorrect regular-expression pattern, and a visual indication of the error-index within the pattern in a full detailed message.
4 getPattern() String It returns the regular-expression pattern which is incorrect.

Inherited Methods From java.lang.Throwable Class

As PatternSyntaxException class extends from Throwable class, below methods are inherited from it.

S. No. Method Name Modifier Description
1. addSuppressed(Throwable exception) void This method is thread-safe which appends the specified exception to the exceptions that were suppressed in order to deliver this exception.
2. getCause() Throwable It returns the cause of this throwable or null if the cause is nonexistent or unknown. 
3. getStackTrace() StackTraceElement[] It provides programmatic access to the stack trace information printed by printStackTrace() method.
4. initCause(Throwable cause) Throwable This method initializes the cause of this throwable to the specified value.
5. printStackTrace(PrintStream s) void Method prints this throwable and its backtrace to the specified print stream.
6. setStackTrace(StackTraceElement[] stackTrace) void This method is designed for use by RPC frameworks and other advanced systems which allows the client to override the default stack trace. It sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods.
7. fillInStackTrace() Throwable This method records within this Throwable object information about the current state of the stack frames for the current thread and fills in the execution stack trace.
8. getLocalizedMessage() String This method creates a localized description of this throwable.
9. getSuppressed() Throwable[] It returns an array containing all of the exceptions that were suppressed in order to deliver this exception.
10. printStackTrace() void It prints this throwable and its backtrace to the standard error stream.
11. printStackTrace(PrintWriter s) void It prints this throwable and its backtrace to the specified print writer.
12. toString() String It returns a short description of this throwable with the name of the class of this object, “: ” (a colon and a space), and the result of invoking this object’s getLocalizedMessage() method.

Inherited Methods From java.lang.Object Class

As PatternSyntaxException class extends from Object class, below methods are inherited from it.

S. No. Method Name Modifier Description
1. equals(Object obj) boolean Indicates whether some other object is “equal to” this one or not.
2. wait() void It causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
3. wait(long timeout) void It causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or the amount of time that is specified in the parameter has elapsed.
4. notifyAll() void It wakes up all the threads that are waiting on this object’s monitor.
5. hashCode() int It returns a hash code value for this object.
6. clone() protected Object It creates and returns a copy of this object.
7. finalize() protected void It is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. We can perform cleanup actions before the object is irrevocably discarded.
8. wait(long timeout, int nanos) void It causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time that is specified has elapsed.
9. notify()  void It wakes up a single thread that is waiting on this object’s monitor.
10. getClass() Class<?> It returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

Example 1: Create a class “Demo1” to replace all non-alphanumeric characters with space in the given message using Regular expression.

Java




// Java program to demonstrate the working
// of PatternSyntaxException class methods
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
  
public class Demo1 {
    private static String REGEX = "?[^a-zA-Z0-9]";
    private static String MSG
        = "Learn/ java? in GeeksforGeeks!!";
    private static String REPLACE = " ";
  
    public static void main(String[] args)
    {
  
        try {
            // Get Pattern class object to compile the
            // regular expression.
            Pattern pattern = Pattern.compile(REGEX);
  
            // Get a matcher object
            Matcher matcher = pattern.matcher(MSG);
  
            // Using matcher object, replace the string
            MSG = matcher.replaceAll(REPLACE);
  
            // catch block to handle PatternSyntaxException.
        }
        catch (PatternSyntaxException pse) {
            System.out.println("PatternSyntaxException: ");
            System.out.println("Description: "
                               + pse.getDescription());
            System.out.println("Index: " + pse.getIndex());
            System.out.println("Message: "
                               + pse.getMessage());
            System.out.println("Pattern: "
                               + pse.getPattern());
            System.exit(0);
        }
  
        System.out.println("Output: " + MSG);
    }
}


Output

PatternSyntaxException: 
Description: Dangling meta character '?'
Index: 0
Message: Dangling meta character '?' near index 0
?[^a-zA-Z0-9]
^
Pattern: ?[^a-zA-Z0-9]
  • In this example, we are trying to replace all the non-alphanumeric characters with a space.
  • But in regex, there is ‘?‘ which is causing the error. Whenever we are working with meta characters like ‘+‘,’*‘,’?‘, we need to be more careful and should use escape characters.
  • As it is causing the error, we can see the Exception details with the index and the regex pattern in the output.

Example 2: Create a class “Demo2” to find the matching pattern in the given message.

Java




// Java program to demonstrate the working
// of PatternSyntaxException class methods
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
  
public class Demo2 {
  
    private static String REGEX = "[Geek";
    private static String MSG
        = "Hi Geek, Welcome to GeeksforGeeks!!";
  
    public static void main(String[] args)
    {
  
        Pattern pattern = null;
        Matcher matcher = null;
        try {
            pattern = Pattern.compile(REGEX);
            matcher = pattern.matcher(MSG);
        }
        catch (PatternSyntaxException pse) {
            System.out.println("PatternSyntaxException: ");
            System.out.println("Pattern: "
                               + pse.getPattern());
            System.out.println("Description: "
                               + pse.getDescription());
            System.out.println("Message: "
                               + pse.getMessage());
            System.out.println("Index: " + pse.getIndex());
            System.exit(0);
        }
        boolean found = false;
        while (matcher.find()) {
            System.out.println("Found the text at "
                               + matcher.start());
            found = true;
        }
        if (!found) {
            System.out.println("No match found!");
        }
    }
}


Output

PatternSyntaxException: 
Pattern: [Geek
Description: Unclosed character class
Message: Unclosed character class near index 4
[Geek
    ^
Index: 4

Note: 

  • This is a common mistake in which the programmer has forgotten the closing parenthesis in the regular expression.
  • So, the output is showing the complete details with the error message and the index of it.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!