- 1AclNotFoundException in Java
- 2ActivationException in Java
- 3AlreadyBoundException in Java
- 4ApplicationException in Java
- 5AWTException in Java
- 6BackingStoreException in Java
- 7BadAttributeValueExpException in Java
- 8BadBinaryOpValueExpException in Java
- 9BadLocationException in Java
- 10BadStringOperationException in Java
- 11BrokenBarrierException in Java
- 12CertificateException in Java
- 13CloneNotSupportedException in Java
- 14DataFormatException in Java
- 15DatatypeConfigurationException in Java
- 16DestroyFailedException in Java
- 17ExecutionException in Java
- 18ExpandVetoException in Java
- 19FontFormatException in Java
- 20GeneralSecurityException in Java
- 21GSSException in Java
- 22IllegalClassFormatException in Java
- 23InterruptedException in Java
- 24IntrospectionException in Java
- 25InvalidApplicationException in Java
- 26InvalidMidiDataException in Java
- 27InvalidPreferencesFormatException in Java
- 28InvalidTargetObjectTypeException in Java
- 29IOException in Java
- 30JAXBException in Java
- 31JMException in Java
- 32KeySelectorException in Java
- 33LambdaConversionException in Java
- 34LastOwnerException in Java
- 35LineUnavailableException in Java
- 36MarshalException in Java
- 37MidiUnavailableException in Java
- 38MimeTypeParseException in Java
- 39NamingException in Java
- 40NoninvertibleTransformException in Java
- 41NotBoundException in Java
- 42NotOwnerException in Java
- 43ParseException in Java
- 44ParserConfigurationException in Java
- 45PrinterException in Java
- 46PrintException in Java
- 47PrivilegedActionException in Java
- 48PropertyVetoException in Java
- 49ReflectiveOperationException in Java
- 50RefreshFailedException in Java
- 51RemarshalException in Java
- 52RuntimeException in Java
- 53SAXException in Java
- 54Java ScriptException
- 55Java ServerNotActiveException
- 56Java SOAPException
- 57Java SQLException
- 58Java TimeoutException
- 59Java TooManyListenersException
- 60Java TransformerException
- 61Java TransformException
- 62Java UnmodifiableClassException
- 63Java UnsupportedAudioFileException
- 64Java UnsupportedCallbackException
- 65Java UnsupportedFlavorException
- 66Java UnsupportedLookAndFeelException
- 67Java URIReferenceException
- 68Java URISyntaxException
- 69Java UserException – Custom Exceptions with Examples
- 70Java XAException
- 71Java XMLParseException – XML Parsing and Exception Handling
- 72Java XMLSignatureException
- 73Java XMLStreamException – StAX Parsing Examples
- 74Java XPathException – Complete Guide with Examples
Java ParseException
Introduction to ParseException in Java
Java is a powerful language for handling all kinds of data, but when you're converting strings into structured objects like dates, numbers, or custom data formats, you're stepping into the territory of parsing. And where there's parsing, there's a chance for error. That’s where ParseException
comes in.
This tutorial is designed to be beginner-friendly and will walk you through everything you need to know about ParseException
—from what it is and when it occurs, to how to handle it gracefully using try-catch blocks.
What is ParseException?
ParseException
is a checked exception defined in the java.text
package. It is thrown when a string that is supposed to follow a specific format (like a date or number) does not match that expected pattern during parsing.
Class Hierarchy
java.lang.Object
↳ java.lang.Throwable
↳ java.lang.Exception
↳ java.text.ParseException
When Does ParseException Occur?
This exception commonly occurs when:
- Parsing a date string with
SimpleDateFormat
- Parsing numbers or formatted strings with
DecimalFormat
- Custom parsing logic fails to read the input string as expected
Constructor Summary
ParseException(String message, int errorOffset)
message – explanation of the error
errorOffset – the position in the input string where the error occurred
Example 1: ParseException with Date Parsing
Let’s try to parse a date string for our fictional fruit delivery app that schedules cherries.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateParseExample {
public static void main(String[] args) {
String dateString = "2024-25-12"; // Invalid date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(dateString);
System.out.println("Parsed date: " + date);
} catch (ParseException e) {
System.out.println("ParseException: " + e.getMessage());
System.out.println("Error at position: " + e.getErrorOffset());
}
}
}
ParseException: Unparseable date: "2024-25-12"
Error at position: 5
Explanation
The input "2024-25-12"
is incorrectly formatted—the month value “25” exceeds valid range (1–12). So, SimpleDateFormat
throws a ParseException
.
Example 2: Handling Multiple Date Formats Gracefully
If your users might enter dates in different formats, consider handling multiple patterns safely.
public class FlexibleDateParser {
public static void main(String[] args) {
String[] dateFormats = { "yyyy-MM-dd", "dd/MM/yyyy", "MMM dd, yyyy" };
String input = "25/12/2024";
boolean parsed = false;
for (String pattern : dateFormats) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date = sdf.parse(input);
System.out.println("Successfully parsed using format '" + pattern + "': " + date);
parsed = true;
break;
} catch (ParseException e) {
System.out.println("Tried format '" + pattern + "' – failed.");
}
}
if (!parsed) {
System.out.println("Could not parse the input date.");
}
}
}
Tried format 'yyyy-MM-dd' – failed.
Successfully parsed using format 'dd/MM/yyyy': Wed Dec 25 00:00:00 IST 2024
Explanation
This approach tries different formats until one works, increasing flexibility for real-world inputs.
How to Avoid ParseException
- Validate input before parsing
- Use
try-catch
blocks to catch and handle exceptions safely - Provide meaningful error messages to users
- Use ISO standard formats (like
yyyy-MM-dd
) wherever possible
Best Practices for Date Parsing
- Use
SimpleDateFormat
carefully—it’s not thread-safe - For thread-safe date formatting, use
java.time.format.DateTimeFormatter
(Java 8+) - Check inputs using regex or UI validation before attempting to parse
Common Mistakes and Fixes
Mistake | Fix |
---|---|
Invalid date format string | Match input exactly to SimpleDateFormat pattern |
Missing error handling | Wrap parsing in try-catch block |
Assuming input is always valid | Validate or sanitize inputs before parsing |
Real-World Analogy
Imagine someone writes a fruit delivery date as “Banana-30-2024” instead of “2024-12-30.” When your app tries to parse this using a date format, it can’t make sense of it. That’s what a ParseException
is: Java’s way of saying, “This doesn’t match the recipe I expected.”
Recap
ParseException
is a checked exception thrown when parsing fails- Use
SimpleDateFormat
or similar classes carefully - Always validate and handle bad inputs with try-catch blocks
- Offer friendly messages to users on failure
Conclusion
Parsing strings into structured data is a common task in Java, especially in real-world applications like billing, inventory, scheduling, and user data entry. But user input is rarely perfect. That’s why ParseException
exists—to help your app say, “Hold on, I didn’t understand that,” rather than crash unexpectedly.
Comments
Loading comments...