ParseException是否仅在字符串转日期时抛出?求其他触发场景示例
Great question! It’s totally normal to only encounter ParseException in date-parsing examples at first—this exception is actually more versatile than that. It’s a checked exception thrown whenever a structured string fails to match the expected format for a specific data type or API. Let’s walk through some underrated scenarios with code examples:
1. Number Format Parsing
When using java.text.NumberFormat to parse strings into numbers, any input that doesn’t conform to valid number formatting (like unexpected non-numeric characters) will trigger a ParseException:
import java.text.NumberFormat; import java.text.ParseException; public class NumberParseDemo { public static void main(String[] args) { NumberFormat numberFormatter = NumberFormat.getInstance(); try { // Attempt to parse a string with invalid non-numeric characters numberFormatter.parse("123.45abc"); } catch (ParseException e) { System.out.println("Number parsing failed: " + e.getMessage()); // Output: Number parsing failed: Unparseable number: "123.45abc" } } }
2. Swing MaskFormatter Input Validation
Swing’s MaskFormatter uses ParseException to enforce strict input formats (like phone numbers, zip codes, or IDs). If the input doesn’t match the defined mask, it throws the exception:
import javax.swing.text.MaskFormatter; import java.text.ParseException; public class MaskFormatterDemo { public static void main(String[] args) { try { // Define a mask for a 3-digit area code + 7-digit phone number MaskFormatter phoneFormatter = new MaskFormatter("###-#######"); phoneFormatter.setValueContainsLiteralCharacters(false); // Input doesn't match the mask (too many digits in area code) phoneFormatter.stringToValue("1234-5678901"); } catch (ParseException e) { System.out.println("Input format invalid: " + e.getMessage()); // Output: Input format invalid: stringToValue failed } } }
3. XML/SAX Parsing Errors
The SAXParseException (a subclass of ParseException) is thrown when parsing malformed XML with SAX parsers. This includes issues like unclosed tags, invalid characters, or broken XML structure:
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXParseException; public class XmlParseDemo { public static void main(String[] args) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); // Parse XML with an unclosed <item> tag parser.parse("<root><item>laptop <item>phone</root>", null); } catch (SAXParseException e) { System.out.println("XML parsing failed: " + e.getMessage()); // Output: XML parsing failed: The element type "item" must be terminated by the matching end-tag "</item>". } catch (Exception e) { e.printStackTrace(); } } }
4. Third-Party CSV Parsing
Many CSV parsing libraries (like OpenCSV) use ParseException to signal invalid CSV formatting—such as unclosed quotes, mismatched delimiters, or malformed rows:
import com.opencsv.CSVReader; import java.io.StringReader; import java.text.ParseException; public class CsvParseDemo { public static void main(String[] args) { try { // CSV with an unclosed quote in the second row String badCsv = "name,age\nAlice,30\nBob,\"25"; CSVReader reader = new CSVReader(new StringReader(badCsv)); while (reader.readNext() != null) { // Attempt to read rows } } catch (ParseException e) { System.out.println("CSV parsing failed: " + e.getMessage()); // Output: CSV parsing failed: Unterminated quoted field at end of line } catch (Exception e) { e.printStackTrace(); } } }
Key Takeaway
At its core, ParseException is all about failed structured string parsing. Any API that expects a string to follow a strict format (dates, numbers, XML, formatted input, CSV, etc.) can throw this exception when the input doesn’t meet those expectations. Date parsing is just the most commonly cited example!
内容的提问来源于stack exchange,提问作者Vũ Minh Vương

