• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this the way to use finally and try with resources ?  RSS feed

 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written two programs.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Same program with try with resources.


Just want to know did I make use of finally and try with resources correctly? or do I have to improve it if yes then how ?

as I know, a try can have only one finally block and is used to recover resources and close objects created to free memory. try with resources reduces code of catch and finally. we don't have to catch exceptions and recover resources using finally it is done by try with resources it self so reduces code writing and makes it simple. Hope I'm on correct path ?
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code is correct.

Small improvements are
class name should start with capital letter (Logfile)
instance variables should be defined with private access modifier
semicolon is not needed in try with resource block if only one resource is mentioned.

as I know, a try can have only one finally block and is used to recover resources and close objects created to free memory.
This is correct.

try with resources reduces code of catch and finally. we don't have to catch exceptions and recover resources using finally it is done by try with resources it self so reduces code writing and makes it simple.
This is not correct.
A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Because the FileOutputStream instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method FileOutputStream.write() throwing an IOException).
So we can say that - try with resources reduces code of finally (not catch).
If exceptions are thrown from both the try block and the try-with-resources statement, then the method logWriter() throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed.You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes i know class name should start with capital letter but I forgot that and
instance variables should be defined with private access modifier semicolon is not needed in try with resource block if only one resource is mentioned.

I never paid attention to this though I read about it. Thank you for try with resources information. Need a lot of practice because I read that already in JLS and forget while coding.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first version is incorrect because you are not closing the Stream (line 21). Line 29 does not appear to throw any checked Exceptions.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you meant this line ?


Line 21 is in constructor where I instantiated an object of FileOutputStream to write bytes to file so why should I close stream before using it ?

Line 29 I did throw IOException what else I need to throw

Checked
Exception
IOException : Did throw this one
FileNotFoundException : Did while creating an object of FileOutputStream
ParseException :
ClassNotFoundException :
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException

Which one do you think I should throw if possible can you please elaborate..
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you instantiated an object in line 21; where do you close it?
Actually, I may be mistaken about IOExceptions; you may suffer an Exception from the finally. The finally should be inside a try.

Create your readers and writers for files as local variables. Don't make them fields.
 
Tim Holloway
Saloon Keeper
Posts: 18789
74
Android Eclipse IDE Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to close the outputstream. If you do not, the buffers may not flush out and you can lose data. Plus, even if you don't, the close of the physical disk file (or whatever) would have to wait until the garbage collector got around to destroying the output stream object, which means that other apps might see incomplete data for an indefinite period of time.

This sort of cleanup has actually become more of a thing now that we have "try with resources", since the scope of the "tried" object is more precisely limited and therefore there's an obvious point after which resources can be freed and cleaner (as for example, closing the file). I ran into this in Spring Data Neo4j, where they've redefined some of their functions to allow for that instead of requiring explicit cleanup.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you instantiated an object in line 21; where do you close it?

In private method logWrite i closed that after use



you may suffer an Exception from the finally. The finally should be inside a try.


Opps ! I didn't think of that, never knew finally could be inside try. This is what happens when you skip a part of topic. I skipped that while reading JLS.

Create your readers and writers for files as local variables. Don't make them fields.

ya I was also skeptical about that but had habit of making them fields in college, yes will get rid of this habit ASAP.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Tim ya got it, thank you for such precious information. Before I was like, wants to write a program which writes text into the file? I was like oh its very easy! but now I'm getting, its not that easy, need to take care of performance as well as memory and neat code.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ganish Patil wrote: . . .
In private method logWrite i closed that after use

. . .
The private method may be called more than once. You are now trying to write to a closed Writer. That problem would not have occurred if you had that Writer as a local variable.

Since Java7 and try‑with‑resources, this sort of ugly code has no longer been necessary:-
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are simply writing text to a file consider using a Formatter.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The private method may be called more than once.
really splendid. thank you Campbell. I wish would have had teacher like you in my 6 years of education.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:

Actually, for those working with older Java versions, the correct way of doing this is:

you should never exit a finally clause abruptly (through an exception or a return statement)
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote: . . .
Actually, for those working with older Java versions, the correct way of doing this is:
. . .
Thank goodness for try‑with‑resources.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!