Search code examples
javaoutputstreamtry-catch-finallyfinallytry-finally

Different behaviors when return place inside and after try


I have following two code block, which I use to compress a String.

code 1

public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
    } finally {
        deflaterOutputStream.close();
    }
}

code 2

 public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
    } finally {
        deflaterOutputStream.close();
    }
    return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
}

Only the second method works fine where first method always return an empty String. I understand the this different behavior occurs due to different placement of return block with respect to finally block. What is the exact behavior for this?


Solution

  • The reason is because in the first method the return statement is executed before you do the deflaterOutputStream.close(); While the second do the close operation first

    deflaterOutputStream writes the data to byteArrayOutputStream when it close the connection. Until deflaterOutputStream is closed, byteArrayOutputStream doesn't contain data.