The Wayback Machine - http://web.archive.org/web/20240909165120/https://www.geeksforgeeks.org/patternsyntaxexception-class-in-java/
Open In App

PatternSyntaxException Class in Java

Last Updated : 16 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

Image

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.


Similar Reads

Java PatternSyntaxException Class getIndex() Method with Examples
Java PatternSyntaxException Class is defined under the java.util.regex package and it depicts unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax, public class PatternSyntaxException extends IllegalArgumentExceptionPatternSyntaxException::getIndex() This method is used t
2 min read
Java PatternSyntaxException Class getDescription() Method with Examples
Java PatternSyntaxException Class is defined under the java.util.regex package and it focuses upon the unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax. Syntax: public class PatternSyntaxException extends IllegalArgumentException This class has the following construct
4 min read
Java PatternSyntaxException Class getPattern() Method with Examples
Java provides Regular Expressions or Regex (in short) API for creating string patterns to search, manipulate, and edit a string in Java. This class is defined under the java.util.regex package and it focuses upon the unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax, S
4 min read
Java PatternSyntaxException Class getMessage() Method with Examples
Java provides Regular Expressions or Regex (in short) API for creating string patterns to search, manipulate, and edit a string in Java. This class is defined under the java.util.regex package and it focuses upon the unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax, S
4 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair&lt;Integer, String&gt; pair = new Pair&lt;Integer, String&gt;( Integer.valueOf(1), &quot;GeeksforGeeks&quot;); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet&lt;String, String, String, String&gt; quartet = new Quartet&lt;String, String, String, String&gt;( &quot;Quartet&quot;, &quot;Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet&lt;String, String, String&gt; triplet = new Triplet&lt;String, String, String&gt;( &quot;Triplet 1&quot;, &quot;1&quot;, &quot;GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Practice Tags :