Search code examples
javagrailssaxparser

Using java exception for condition checking


I'm creating a single xml file uploader in my grails application. There is two types of files, Ap and ApWithVendor. I would like to auto detect the file type and convert the xml to the correct object using SAXParser.

What I've been doing is throwing an exception when the sax parser is unable to find a qName match within the the first Ap object using the endElement method. I then catch the exception and try the the ApWithVendor object.

My question is there a better way to do this without doing my condition checking with exceptions?

Code example

        try {
            System.out.println("ApBatch");
            Batch<ApBatchEntry> batch = new ApBatchConverter().convertFromXML(new String(xmlDocument, StandardCharsets.UTF_8));

            byte[] xml = new ApBatchConverter().convertToXML(batch, true);
            String xmlString = new String(xml, StandardCharsets.UTF_8);
            System.out.println(xmlString);

            errors = client.validateApBatch(batch);
            if (!errors.isEmpty()) {
                throw new BatchValidationException(errors);
            }

            return;
        } catch (BatchConverterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            System.out.println("ApVendorBatch");
            Batch<ApWithVendorBatchEntry> batch = new ApWithVendorBatchConverter().convertFromXML(new String(xmlDocument, StandardCharsets.UTF_8));

            byte[] xml = new ApWithVendorBatchConverter().convertToXML(batch, true);
            String xmlString = new String(xml, StandardCharsets.UTF_8);
            System.out.println(xmlString);

            errors = client.validateApWithVendorBatch(batch);
            if (!errors.isEmpty()) {
                throw new BatchValidationException(errors);
            }

            return;
        } catch (BatchConverterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Solution

  • You can always iterate over the nodes in the XML and base decision on the fact that specific Node is missing (or is present - or has specific value) (see DocumentBuilder and Document class)

    Using exceptions for decision-making or flow-control in 99% situations is considered bad practice.