This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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: 3599
    
  14

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

Joined: Oct 27, 2005
Posts: 19654
    
  18

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: 3599
    
  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: 19654
    
  18

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.
 
 
subject: try-with-resources
 
Similar Threads
Good Programming Practice
Can you have a try/catch inside a try
break out of SAX parsing
Exception Doubt
handling error when using jsp:include