This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Features new in Java 7 and the fly likes try-with-resources Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Features new in Java 7
Bookmark "try-with-resources" Watch "try-with-resources" New topic
Author

try-with-resources

Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

i really like this new feature. when you do IO you only need try and catch. not try, catch, and finally(to close).


SCJP
Visit my download page
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

Actually, you don't even need a catch. You can just use the try clause.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

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".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

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

Joined: Oct 27, 2005
Posts: 19684
    
  20

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: try-with-resources