简体   繁体   中英

Java : Why exception is not being caught inside the Second Method catch block

I have this method calling the below method , i am purposufully providing a wrong port number for the URL to be connected . But to my surprise , the exception produced is being caught in first Method catch block Why it is not being handled inside the executeData Method's catch block ??

**1st Method** 
public APIResponse execute(Request request, Class<? extends Response> responseClass) {
        try {
        String xmlResponse = executeData(request);
                  // some code
        return response;
        }
        catch (Exception ex) {

            return new Response(ErrorCode.SYSTEM_ERROR);
        }
    }

2nd Method
public String executeData(Request request) throws IOException {
        URL url = null;
        URLConnection urlc = null;
        try {
            url = new URL("http://localhost:80870/");
            urlc = url.openConnection();

        }
        catch (Exception ex) {
        ex.printStackTrace();
**// This is not being executed .**
        }

                           // Some code
                   // Some code
        return xmlResponse;
    }

That's probably because your line

// some code

produces another exception that is caught. Your 2nd method does not throw any exception, I see nothing wrong with that.

connection.connect();

Will throw the exception.

You could also check for the status:

int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    // Not OK.
}

I guess exception occured in

// some code //some code

after catch block in executeData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM