• Post Reply Bookmark Topic Watch Topic
  • New Topic

try with resources  RSS feed

 
Randall Twede
Ranch Hand
Posts: 4692
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am looking over some of my old (poorly written) code. i want to try to do IO the same for all of them, and do it properly. the way i was doing it was a try block that called a private method to do the reading. it had a catch block, but no finally
as i look at try with resources you declare the resource in the try statement. here i will show an example

should i get rid of the private method? or what?
perhaps something like this?
 
Paul Clapham
Sheriff
Posts: 22708
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the (main) point of try-with-resources is to get the resources closed automatically at the end of the block. You'll notice you aren't closing your BufferedReader, and that's what try-with-resources does for you.

So no, you can leave the private method as is, just use try-with-resources inside it. As far as I know (and I don't have Java 7 on this machine to test it) the try-with-resources version of the try-block doesn't require a catch-block.
 
Stephan van Hulst
Saloon Keeper
Posts: 7932
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always consider try-with-resources as syntactic sugar for a try-finally block.
Is equivalent to:
Except that in the second piece, scanner is also available outside the scope of the try block, which is usually not what you need.
 
Stephan van Hulst
Saloon Keeper
Posts: 7932
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Except I'm not sure what the try-with-resources does with the exception that an AutoCloseable can throw. I suppose it just propagates it upward, and you'll have to catch it or declare it in the method if it's checked.
 
Randall Twede
Ranch Hand
Posts: 4692
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i got it. just move the try with resources to the private method(like my second example). you do still need to(or at least should...not certain...the examples i see have catch blocks or throw) catch or propagate exceptions. you just no longer forget(like i did) to close the resource. i like it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!