我有一个处理大量数据的批处理作业。该作业基本上从源数据库获取数据并进行 Web 服务调用,然后将数据写入目标数据库。 今天我遇到了“NPE”,我在其中检查 XML 是否有“成功”响应。我检查其中一个节点以确定响应是成功还是失败。 我可以有一个 try 和 catch block ,但我需要知道这是否是正确且有效的方法。
代码
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 block 来处理 NPE 是否是一个好方法。请指教
谢谢
最佳答案
如果您愿意,可以使用 try catch block ,但在调用父对象的任何方法之前检查父对象是否为 null 可能会更干净、更高效,即
if (null != document) {
NodeList nodelist = document...
}
但是,您可能希望将整个事情包装在 try catch 中,因为在某些情况下这些方法可能会抛出 NPE 以外的其他异常。
关于java - 在批处理运行期间检查 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522863/