在批处理运行期间检查 NPE

我有一个处理大量数据的批处理作业。该作业基本上从源数据库获取数据并进行 Web 服务调用,然后将数据写入目标数据库。今天我遇到了“NPE”,在那里我检查了 XML 的“成功”响应。我检查其中一个节点以确定响应是成功还是失败。我可以有一个 try 和 catch 块,但我需要知道这是否是正确和有效的方法。


代码


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();


        InputSource source = new InputSource();

        source.setCharacterStream(new StringReader(response));

        Document document = builder.parse(source);


        XPath xpath = XPathFactory.newInstance().newXPath();

        NodeList nodeList = document.getElementsByTagName(DCDirectProcessorConstants.Tag_Response_getValue);

        Node node = nodeList.item( 0 ).getAttributes().getNamedItem(DCDirectProcessorConstants.Tag_Response_Status);


`Node node = nodeList.item( 0 ).getAttributes().getNamedItem(DCDirectProcessorConstants.Tag_Response_Status);` line throws NPE. 

堆栈跟踪


java.lang.NullPointerException at com.mercuryinsurance.r3.util.MigrationExecutorThread.run(MigrationExecutorThrea .java:96) [migration.jar:?] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_66] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_66] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_66]


因此,在该行中,我只是检查标记的值是否为“成功”,不确定是否是使用 try 和 catch 块来处理 NPE 的好方法。请指教


互换的青春
浏览 110回答 1
1回答

婷婷同学_

如果愿意,您可以使用 try catch 块,但在调用父对象的任何方法之前检查父对象是否为空可能更清晰、更有效,即if (null != document) {    NodeList nodelist = document...}但是,您可能希望将整个内容包装在 try catch 中,因为在某些情况下,这些方法可能会抛出 NPE 以外的其他异常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java