import java.text.ParseException;
public class MyFieldParserExample
{
public String myFieldParser(String inputStr)
throws ParseException
{
int colon = inputStr.indexOf(':');
if(colon == -1) // simple test for ':'
{
throw new ParseException(inputStr, inputStr.length() -1 );
}
// found a colon, we are safe to continue parsing
// ...
// This next line wasn't in the book, and could be
// any parsing. We picked the substring up to, but
// not inluding, the colon.
String parsedString = inputStr.substring(0, colon);
return(parsedString);
}
public void testValue(String s)
{
String beforeColon = null;
try
{
beforeColon = myFieldParser(s);
}
catch (ParseException e)
{
System.out.println(e);
e.printStackTrace();
// You could do more here.
}
}
public static void main(String args[])
{
MyFieldParserExample ex = new MyFieldParserExample();
ex.testValue("This is good:it has a colon.");
ex.testValue("This is bad. It does not have a colon.");
}
}
java.text.ParseException: This is bad. It does not have a colon. java.text.ParseException: This is bad. It does not have a colon. at java.lang.Throwable.fillInStackTrace(Native Method) at java.lang.Throwable.(Throwable.java:94) at java.lang.Exception. (Exception.java:42) at java.text.ParseException. (ParseException.java:54) at MyFieldParserExample.myFieldParser(MyFieldParserExample.java:10) at MyFieldParserExample.testValue(MyFieldParserExample.java:26) at MyFieldParserExample.main(MyFieldParserExample.java:40)
--- Output Ends ---
- javac MyFieldParserExample.java
- java MyFieldParserExample