This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try-with-resources

 
Randall Twede
Ranch Hand
Posts: 4385
3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i really like this new feature. when you do IO you only need try and catch. not try, catch, and finally(to close).
 
Stephan van Hulst
Bartender
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, you don't even need a catch. You can just use the try clause.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The catch rules haven't changed - you either catch or declare it in a throws clause. All try-with-resources provides is a finally block that closes all resources declared in the "header".
 
Stephan van Hulst
Bartender
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the object is an AutoCloseable that doesn't throw any checked exceptions, you don't need to declare anything at all

 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Except the Scanner, which is what I was referring to. And the close() method can throw any exception it wants to, as it's suppressed by the try-with-resources block.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic