On Tue, 19 Sep 2023 16:30:07 GMT, Harshitha Onkar <[email protected]> wrote:

>>> Better to close the stream objects in finally block in case of Exception.
>>> 
>>> ```
>>> finally  {
>>>      if (oos != null) {
>>>          oos.close();
>>>      }
>>>      if (ois != null) {
>>>           ois.close();
>>>      }
>>>   } 
>>> ```
>> 
>> No, *it's not better.* If `oos.close()` throws an exception, then `ois` is 
>> left open. In addition to that, any exception thrown from the finally block 
>> will replace the exception thrown from the try block.
>> 
>> *The best way is using 
>> [**try-with-resources**](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)*:
>>  it handles all the above correctly.
>
> Noted. Thanks!

Right, I looked into Aleksey's suggestion for try-with-resources and learned 
that this should handle things correctly. This is applicable when objects like 
streams or writers need to be closed for example. Thanks for taking a look!

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/15755#discussion_r1330411187

Reply via email to