return 放在内部和尝试后的不同行为

Different behaviors when return place inside and after try

我有以下两个代码块,用于压缩字符串。

代码 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();
    }
}

代码 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);
}

只有第二种方法可以正常工作,而第一种方法总是 return 一个空字符串。我知道这种不同的行为是由于 return 块相对于 finally 块的不同放置而发生的。这个的确切行为是什么?

原因是因为在第一种方法中 return 语句在执行 deflaterOutputStream.close(); 之前执行,而第二种方法首先执行关闭操作

deflaterOutputStream 在关闭连接时将数据写入 byteArrayOutputStream。在 deflaterOutputStream 关闭之前,byteArrayOutputStream 不包含数据。

在第二个示例中,byteArrayOutputStream 被填充,因为 deflaterOutputStream 已关闭并且 已刷新

即使您将 return 语句放在 try 块中,您的 finally 块也会执行,finally 块的功能是

If exception raised or not raised, even though if exception raised and handled or not handled then finally block will execute, finally block won't execute if you place system.exit() in try or catch block

在你的代码中

try{
return------> this wont return instead finally block will execute
}
finally{
//
}

您的关闭 DeflaterOutputStream 并且它已刷新,因此它返回空值