PatternSyntaxException Class in Java
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
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 {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(MSG);
MSG = matcher.replaceAll(REPLACE);
}
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
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
Pattern Class in Java
The Pattern class in Java is used for defining regular expressions (regex) to perform pattern matching on strings. It is part of the java.util.regex package and it plays a key role in searching, replacing, and manipulating strings based on patterns. The Matcher class works together with Pattern to p
3 min read
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 IllegalArgumentExceptionPatter
2 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. Th
4 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 IllegalArgume
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. Th
4 min read
StreamCorruptedException in Java
The class StreamCorruptedException of ObjectStreamException is an exception thrown when control information that was read from an object stream violates internal consistency checks. It will create a StreamCorruptedException and list a reason why the exception was thrown. If no parameters are passed
3 min read
java.net.SocketException in Java with Examples
SocketException is a subclass of IOException so it's a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is: java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.n
5 min read
NotSerializableException in Java with Examples
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies. The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deseri
4 min read
NumberFormatException in Java with Examples
The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. It
3 min read
Wrapper Classes in Java
A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
6 min read