It's not a secret anymore!
The moose likes Beginning Java and the fly likes try and catch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "try and catch" Watch "try and catch" New topic
Author

try and catch

Ozzy Boshi
Greenhorn

Joined: Sep 21, 2012
Posts: 7
I recently found a code snippet that use the try...catch construct in a weird way, the try word is followed by round brackets.
Within the round brackets a new object is build.

What if i build the object on the previous line where the try word is declared?
What's the difference?

for example... try (Scanner scanner = new Scanner(path, ENCODING.name())){

Thanks in advance.

Ankit Dan
Ranch Hand

Joined: Aug 31, 2012
Posts: 47

It is called "try with resources"...It helps to manage any resources which otherwise a programmer has to manage manually
the resource will be automatically taken care of as soon as the try block has finished its execution
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

In addition to the answer provided by Ankit Dan you might want to read The try-with-resources Statement tutorial to understand the statement better.


The quieter you are, the more you are able to hear.
Ozzy Boshi
Greenhorn

Joined: Sep 21, 2012
Posts: 7
I thank you all.
Now this strange try block makes sense to me.
In the past i would have used the try.. finally statement, it's very similar

Kemal Sokolovic wrote:In addition to the answer provided by Ankit Dan you might want to read The try-with-resources Statement tutorial to understand the statement better.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 63053
    
  69

Note that try-with-resources is new with Java 7.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Ozzy Boshi
Greenhorn

Joined: Sep 21, 2012
Posts: 7
Bear Bibeault wrote:Note that try-with-resources is new with Java 7.


yes, this is mentioned in the article that Kemal Sokolovic suggested.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43377
    
  32
Don’t put System.in as the path in that sort of expression. If the Scanner closes System.in, it may be impossible to reopen it.
Ozzy Boshi
Greenhorn

Joined: Sep 21, 2012
Posts: 7
have you ever tried to do this?
I have never thought about this type of downsides
Campbell Ritchie wrote:Don’t put System.in as the path in that sort of expression. If the Scanner closes System.in, it may be impossible to reopen it.
 
Don't get me started about those stupid light bulbs.
 
subject: try and catch
 
It's not a secret anymore!