Search code examples
javaxmlexceptiontry-catchsax

Catching Exceptions not related to XML while SAX parsing in Java?


I am not educated in catching exceptions in Java so this might be a trivial question:
I parse an XML file, and in the method for endElement I have:

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {

   if (qName.equals("manufacturer")) {
            newManufacturer = false;
            String venueName = manufacturerBuilder.toString();
            event.setVenueName(venueName);
   }
}

If event is null, my program crashes. What I'd like to do is add a couple of instructions for an orderly shutdown in this case (closing db connections etc).

Of course I can do:

try{
   event.setVenueName(venueName);
}
catch (NullPointerException e){
   db.close();
//etc
}

But I have many of these exceptions to catch in the methods of the parser. Can't I just put a try - catch at a higher level that would catch any kind of exception while parsing (such as the one above)? But where exactly?


Solution

  • The fact that your ContentHandler.endElement method is being called at all, indicates you must be passing your ContentHandler object to a parse or unmarshal operation. Put that parse/unmarshal call in a try/finally block:

    try {
        saxParser.parse(source, myHandler);
    } finally {
        db.close();
    }
    

    The finally block will always execute, even if an exception occurs.

    Catching NullPointerException is poor practice. Exceptions are for conditions which should not happen. Usually, a NullPointerException tells you that you have made a mistake in your code.

    In your case, you seem to be storing information from the XML document in your event object. If that object is null, do you really want your program to keep executing, even though you won't be storing the information?

    Usually, the answer is no. In that case, you are better off if you don't catch the exception, so you will be aware that your code did not perform the task you wanted it to perform.

    If you really do want to keep executing, the correct way to handle nulls is not to let the mistake (that is, the NullPointerException) occur, but rather to make sure it never occurs:

    if (event != null) {
        event.setVenueName(venueName);
    }