使用 java 异常进行条件检查

Using java exception for condition checking

我正在我的 grails 应用程序中创建一个 xml 文件上传器。有两种类型的文件,Ap 和 ApWithVendor。我想自动检测文件类型并使用 SAXParser 将 xml 转换为正确的对象。

我一直在做的是当 sax 解析器无法使用 endElement 方法在第一个 Ap 对象中找到 qName 匹配时抛出异常。然后我捕获异常并尝试 ApWithVendor 对象。

我的问题是有没有更好的方法来做到这一点而不用异常检查我的条件?

代码示例

        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();
        }

首先尝试将 XML 字符串转换为 XML 树对象,然后使用 XPath 确定它是否为 ApWithVendor 结构。 IE。检查结构中是否有类似“/application/foo/vendor”路径的元素。 决定后,将 XML 树对象转换为对象。

您始终可以遍历 XML 中的节点,并根据特定节点缺失(或存在 - 或具有特定值)这一事实做出决定(参见 DocumentBuilderDocument class)

在 99% 的情况下使用异常进行决策或流程控制被认为是不好的做法。