Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中catch块中返回的奇怪问题_Java_Exception_Return_Catch Block - Fatal编程技术网

Java中catch块中返回的奇怪问题

Java中catch块中返回的奇怪问题,java,exception,return,catch-block,Java,Exception,Return,Catch Block,我使用的try/catch块有一个奇怪的问题。我有这个方法,它只是从远程服务获取一些数据并存储 public WFSGetCapabilitiesResponse wfsGetCapabilities(String url) { WFSGetCapabilitiesResponse response = new WFSGetCapabilitiesResponse(); try { WFSDataStore data = loadWFSCapabilities(

我使用的try/catch块有一个奇怪的问题。我有这个方法,它只是从远程服务获取一些数据并存储

public WFSGetCapabilitiesResponse wfsGetCapabilities(String url) {
    WFSGetCapabilitiesResponse response = new WFSGetCapabilitiesResponse();

    try {
        WFSDataStore data = loadWFSCapabilities(url);
        String[] typeNames = data.getTypeNames();
        ArrayList<WFSFeatureTypeBase> wfsLayers = new ArrayList<WFSFeatureTypeBase>();
        for (int i = 0; i < typeNames.length; i++) {
            String typeName = typeNames[i];

            WFSFeatureTypeBase newLayer = new WFSFeatureTypeBase();
            newLayer.setTypeName(typeName);
            newLayer.setName(typeName.split(":")[1]);
            newLayer.setTitle(data.getFeatureTypeTitle(typeName));
            newLayer.setAbstract(data.getFeatureTypeAbstract(typeName));
            newLayer.setServiceUrl(url.split("\\?")[0]);

            wfsLayers.add(newLayer);
        }
        response.setWFSLayers(wfsLayers);
    } catch (IOException e) {
        response.setError(WCSCapabilitiesResponse.IO_EXCEPTION);
        response.setErrorMessage(e.getMessage());
        response.setSuccessful(false);
        e.printStackTrace();
        return response;
    }
    return response;
}
如果我用这段代码运行,我会得到一个空指针异常“data”为空,但不知道它是否相关。但是,如果我从catch块中删除return语句,一切都很好

奇怪的是,IOException在这两种情况下都没有被捕获,所以我不明白为什么它会产生如此大的影响

所以再次,在catch块中返回时,它不起作用,没有它,它会起作用。。。我真的不明白为什么会这样


有什么想法吗?

嗯,我的第一个想法是,只有在抛出IOException时,catch块才能发挥作用,所以我们可以肯定这是真的。同样地,我们知道,如果没有catch块,这个异常将从wfsGetCapabilities方法中传播出去,假设您在删除catch块时添加了一个适当的throws声明

因此,在工作情况下,调用代码很可能会捕获更高级别的IOException,并以这样一种方式处理它,即根据输出判断方法是否正常工作。当然,您的方法不起作用,并引发了一个异常,但可能有一个默认的回退或类似的方法在错误情况下被调用


这就是希望处理的奇怪部分。至于问题部分,如果您得到一个与catch块一起抛出的NullPointerException,但不是没有它,那么很明显您的catch块逻辑不太正确,导致了这个问题。从您发布的内容来看,这些直接引用看起来都不是空的-查看堆栈跟踪,确定引发异常的行,然后像其他NPE一样修复异常。

您试图从哪里访问数据?当它为空时,它就工作了。。。。这可能意味着您返回了某种类型的对象,没有记录异常,或者此方法处理的某些业务案例完全正确。