Java Integration
Transform Anything with Java
Handling Exceptions in SAX
For this exercise, we will use the base code of my previous exercise. Here is the link
Let us update the XML file and add some errors. I have updated the third record Item element as wrongitem.
<?xml version="1.0" ?>
<items>
<item id="1">
<name>iPhone 5</name>
<manufacturer>Apple Inc</manufacturer>
<price>600</price>
</item>
<item id="2">
<name>iPhone 6</name>
<manufacturer>Apple Inc</manufacturer>
<price>700</price>
</item>
<item id="3">
<name>Moto X</name>
<manufacturer>Motorola</manufacturer>
<price>200</price>
</wrongitem>
<item id="4">
<name>Moto G</name>
<manufacturer>Motorola</manufacturer>
<price>450</price>
</item>
<item id="5">
<name>Samsung S4</name>
<manufacturer>Samsung Corp</manufacturer>
<price>550</price>
</item>
</items>
Now let us override three more methods.
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning");
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.println("Error");
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fatal");
}
Also in the readDatafromXML() method, we will remove throws SAXException and place the below code.
try {
SAXParser parser = factory.newSAXParser();
parser.parse(new File(filename), this);
} catch (SAXException e) {
System.out.println(e.getMessage());
}
Now let us look at the output.
Fatal
The element type "item" must be terminated by the matching end-tag "</item>".
3
1;Apple Inc;iPhone 5;600
2;Apple Inc;iPhone 6;700
3;Motorola;Moto X;200