Finally block could contain some special things, eg. with incidental variable value changing. But I can't declare variable outside try() block, and give them values inside - so the finally block has chance to see them.
When I do a real job, I had to write adapter class to streams, so I can override theirs "deallocate" method?
Why don't need the finally{} block when I use try-with-resource?
Tárgyalás alatt
Hozzászólások (2)
- Népszerű
- Új
- Régi
Be kell jelentkeznie a hozzászóláshoz
Thomas
29 September 2024, 10:32
try-with-resources has been introduced cause closing streams yourself is kinda messy. Eg. if you'd really want to handle all exceptions that may occur, then you'd need to have a inner try-catch block in finally as close() may also throw an exception
try-with-resourced takes care of closing and it WANTS you to not declare the stream outside as it will do the closing when you leave the construct. Then it also handles all the exceptions. Exceptions that occur when opening or when reading the stream are simple the excepion that ends in the catch block. But there also may be a closing exception and that one may be hidden by other exceptions. You can ask for an array of these suppressed exceptions in the catch block with Throwable[] suppressed = e.getSuppressed();
But you rarely will need this.
In the end the try-with-resources approach is far easier to read and understand
+10
Thomas
29 September 2024, 10:34
Besides for closing streams you still can use finally. That's no problem at all.
+7