File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try and catch

 
Ozzy Boshi
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
Eclipse IDE Java MyEclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 825
5
Java Python Ruby
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ozzy Boshi
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64173
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that try-with-resources is new with Java 7.
 
Ozzy Boshi
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic