Closing URLConnection and InputStream correctly?

Yep.. Doing the end part in finally would be best idea because if code fails somewhere, program won't reach till .close(), .disconnect() statements that we keep before catch statements...

If the code fails somewhere and exception is thrown in between of the program, still finally get executed regardless of exception thrown...


There is also the new (with Java 7) 'try()' technique

        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
        }

Basically, it will auto-close anything in the try() statement, regardless of whether it is successful or not.

Tags:

Java