On Tue, 19 Sep 2023 16:02:21 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.

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

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

Reply via email to