aspose file tools*
The moose likes Features new in Java 7 and the fly likes try-with-resources from Java tutorial Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Features new in Java 7
Bookmark "try-with-resources from Java tutorial" Watch "try-with-resources from Java tutorial" New topic
Author

try-with-resources from Java tutorial

Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

Was going through java 7 tutorial on try-with-resources @ Tutorial Link and caught up with following



For the above code, tutorial says

in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed.


When tested, it seems contrary to me i.e. any exceptions in try-with-resources statement (Line 1) is taking precedence over any exception thrown in tryblock (Line 2). That said, the exception from Line 2 is not thrown at all.

Here is the code that was used to test



Am i missing something here ?


Warm Regards,
Rakesh
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Please give us an example of how your code runs, and which Exception it suffers. Print its stack trace, and its suppressed Exceptions.

If something in the Java Tutorials is confusing, you need to go to the Java Language Specification (LJS), which is the definitive guide. I couldn’t see anything relevant to your problem in the Exceptions chapter, but there is much more in the section about try. It says that exceptions can be added to the suppressed Exception list, which appears to mean the same as the tutorial quote. As I said, let’s see your stack traces first, then we can try to work out what you actually happens.
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

Thanks Ritchie. Updated the original post to include the code.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
What strange code. What is the stack trace?
You need never say if (true)
You appear to be throwing an Exception yourself rather than something going wrong. Try writing to a real file which you have on a memory stick, which you have marked read‑only.
Take off the read‑only tag and try reading the lines to write from the keyboard and writing them to the file. Pull the memory stick out between lines!
Then see what the stack traces look like.
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

It is, indeed, strange code and the idea is to basically test the way try-with-resources behaves.

The posted question is about validating "what tutorial says" about the way try-with-resources handles the exceptions. Especially when they are thrown from both try block and the try-with-resources statement. Whether the exceptions are genuine or explicit is off the topic.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
And what is the stack trace?
If you try to open a nonexistent file, do you ever get to execute the if (true) bit?
Go through the JLS section I posted earlier about Exceptions and find out about suppressed Exceptions. That might help.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Rakesh,

I'm not sure why you're surprised at this behavior. If there's an exception opening the file -- i.e., on the "try" line -- then the body of the try block is never executed. This is by design; it's how it's supposed to work. If the file couldn't be opened, then of course the code that uses the file should not be executed, right? You could consider that one of the features of the try-with-resources construct.


[Jess in Action][AskingGoodQuestions]
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

Ernest Friedman-Hill wrote:Hi Rakesh,

I'm not sure why you're surprised at this behavior. If there's an exception opening the file -- i.e., on the "try" line -- then the body of the try block is never executed. This is by design; it's how it's supposed to work. If the file couldn't be opened, then of course the code that uses the file should not be executed, right? You could consider that one of the features of the try-with-resources construct.


Staright to the point Ernest. Thanks for that. I am afraid that is what my point too. Unless i completely misunderstood, the tutorial says otherwise.
in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed.


Isnt it saying that eventhough the try-with-resources throws an exception, the code actually will execute the try block code and throws that exception ?

@Campbell Ritchie : Thanks for the pointers.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
You’re welcome
But what Exception do you get from that program? What happens if you call its method to show suppressed Exceptions? Your example does appear different from the tutorial example. As I said, and Ernest has confirmed, if you get an Exception opening your Reader, how are you even going to get as far as if (true). How are you going to have another Exception to suppress in the first place?
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48


In the above code, its not possible for br to throw exceptions at both line 1 and line 2 (it can either throw at line 1 or line 2 but not both). That is the reason i added that if block to throw an exception explicitly. I agree that line 2 never gets executed but thats off the point.

In line with what we agreed on earlier, the code after line1 never gets executed. The calling code gets an exception with following stack trace

As expected, since the try block code never gets executed, there is no suppressed exceptions in this case.

Just to summarize, Java behaves perfectly. I am just trying to understand if i am missing something that tutorial points to.

Campbell Ritchie wrote:How are you going to have another Exception to suppress in the first place?

Precisely the question i had. If line 1 throws an exception and the code that follows never gets executed, then why the tutorial says there will be an exception suppressed. Let alone which exception

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Rakesh --

I just read the tutorial page, and now I understand what's happening. They're comparing an old-style example in which a file is closed in a "finally" block, with a new-style example in which the file is closed implicitly by the try-with-resources statement. The exceptions they're talking about all come from closing the file, not from opening it.

What they're saying is that in the old-fashioned code, if you operate on a file, get an exception, then try to close the file in a finally block and close() throws an exception, then the exception thrown by the close() is the one that will propagate out of the method.

On the other hand, in the new-style code, the exception from the close() will be suppressed; the exception throws from inside the try block will be the one to propagate. This is clearly what you want, so it's a good thing.
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

Thanks for the confirmation (and clarification) Ernest. Yes, i agree with the behaviour you mentioned i.e. java 6 and earlier versus java 7. I think the code example (for java7) in the tutorial is missing a finally block.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Rakesh K. Cherukuri wrote:Thanks for the confirmation (and clarification) Ernest. Yes, i agree with the behaviour you mentioned i.e. java 6 and earlier versus java 7. I think the code example (for java7) in the tutorial is missing a finally block.


No, it's not missing, it's just invisible! The whole point (well, the main point) of try-with-resources is that it contains that "missing" finally block, implicitly. Things with a close method can implement the new AutoCloseable interface. Then the object you initialize in try-with-resources gets its close() method called automatically. You don't have to write that code yourself, see?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Aaaaaaaah! That's what it all means.
Rakesh K. Cherukuri
Ranch Hand

Joined: Jun 01, 2010
Posts: 48

Ernest Friedman-Hill wrote:No, it's not missing, it's just invisible! The whole point (well, the main point) of try-with-resources is that it contains that "missing" finally block, implicitly. Things with a close method can implement the new AutoCloseable interface. Then the object you initialize in try-with-resources gets its close() method called automatically. You don't have to write that code yourself, see?

I think i was too quick to point out the tutorial code. You are right. Not sure what should be corrected (if at all) in the tutorial but i understand when Ritchie says
Aaaaaaaah! That's what it all means.
Paul Witten
Ranch Hand

Joined: Oct 10, 2012
Posts: 86
Campbell Ritchie wrote:Pull the memory stick out between lines!

Very slick. It's great to know how to beat HAL like a drum isn't it?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Campbell Ritchie wrote:You need never say if (true)

Well if you take that out, the compiler will complain about unreachable code. So this is a technique to be able to insert code to throw an exception from an arbitrary location without the compiler complaining. No, you should never do this in production code. But it can be a good way to test what can happen in certain situations.
Lok Manick
Ranch Hand

Joined: Jan 24, 2005
Posts: 71
It will all fall back to the answer to the question, can a try block exist with out a catch or finally block...


with regards,
Loks (SCJP, SCWCD)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Lok Manick wrote:It will all fall back to the answer to the question, can a try block exist with out a catch or finally block...
And what did the link in your first post show?
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

Hi Moderators and Ranchers,
Can you please provide a working example which illustrates the combination of try{} block with try-with-resource feature in Java SE 7.help provided will be highly appreciated.
Regards,
Deepak Lal


When The Going Gets Tougher,The Tougher gets Going
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
What is wrong with the the example in the first post in this thread?
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

hi campbell,
i need a working example which has a combination of try{} block with try-with-resource feature in Java SE 7,i need both of them and the tutorial link doesnt speak of that.if a working example is provided it will be helpful.
Please help me campbell.

Regards,
Deepak Lal
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
[campbell@localhost java]$ chmod 000 a*
[campbell@localhost java]$ java TryDemo
java.io.FileNotFoundException: /home/campbell/java/allclasses-frame.html (Permission denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at TryDemo.countLines(TryDemo.java:27)
at TryDemo.main(TryDemo.java:46)
[Ljava.lang.Throwable;@7920afc0
By setting the permissions on that allclasses file to 000 you make it not readable, so you see what happens about the Exception. Note the suppressed Exceptions come out as an array, and you can get its constituent parts by the usual techniques.
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

Campbell Ritchie wrote:


Campbell i have included my code....is it possible to have a normal try{} block with catch(Exception e) in above code with try-with-resouces feature of Java SE 7 feature.

@Campbell,As you compiled the code.if you dont mind could you tell me which are the suppressed warning in your code

(my guess for suppressed warnings is below.
java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
)

Please correct me im wrong.
Thanks for the code.I'm highly grateful to you for a nice code.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
You’re welcome
Unfortunately your additions to my suggestion are poorly indented, so they are difficult to read. Assuming you have those methods implemented and compiled, yes you can nest a try inside another try. Yes you can precede a try with another try‑catch or try‑finally.
If you want fuller details, you would have to go through the grammar in the Java Language Specification.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
There were no suppressed warnings. Go through the links earlier in this thread and you will find out about suppressed exceptions.
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

Campbell Ritchie wrote:You’re welcome
Unfortunately your additions to my suggestion are poorly indented, so they are difficult to read. Assuming you have those methods implemented and compiled, yes you can nest a try inside another try. Yes you can precede a try with another try‑catch or try‑finally.
If you want fuller details, you would have to go through the grammar in the Java Language Specification.


My 2 queries/califications

1> yes i wanted to ask whether i can precede a try with another try-with-resource block as i have done in my code.
2> yes it was a typo mistake,i meant suppressed exceptions.Thanks for correction


Regards,
Deepak Lal
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Deepak Lal wrote: . . .
1> yes i wanted to ask whether i can precede a try with another try-with-resource block as i have done in my code. . . .
Quote probably, yes. Don’t know about nesting them. Why not try it.
James X Peterson
Whizlabs Java Support
Ranch Hand

Joined: Feb 26, 2013
Posts: 158
Hi ,

I think following link will help you.

http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

Regards,
James
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

james,unfortunate to say the tutorial link does not have a working example.so i asked campbells help

--
Deepak Lal
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
There is a working example (I think) in the first post in this thread.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
The example in the first post was copied from the article linked in that same first post, which is the tutorial. James posted a link to another copy of the same tutorial, with the same content. Which still has the same working example right at the very beginning. It's all the same thing.

Deepak, on the other hand, was asking about a working example which combines try-with-resources with a traditional try block. The tutorial does have an example of that as well (at least, one way to do it), but it's further down the page:

I'm not sure if there are still unanswered questions remaining.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
I misunderstood the bit about the combination. Sorry.
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

Mike simmons, i beg to differ with you. your example is only having try with resource block.

My requirement is ....is it possible to have a normal try{} block with catch(Exception e) in above code with try-with-resouces feature of Java SE 7 feature.

some thing like




is this possible?can we have a working example for above scenario.(a combination of try block with try with resources)..Please let me know in case you need more clarification @Simon,@Campbell

Please reply

Regards,
Deepak Lal
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Deepak Lal wrote: . . .

My requirement is ....is it possible to have a normal try{} block with catch(Exception e) in above code with try-with-resouces feature of Java SE 7 feature.



is this possible?can we have a working example for above scenario. . . .
I have taken your code and expanded it a bit.
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

Thanks Campbell.
Shiv Swaminathan
Ranch Hand

Joined: Jul 21, 2010
Posts: 48

My requirement is ....is it possible to have a normal try{} block with catch(Exception e) in above code with try-with-resources feature of Java SE 7 feature.


Based on my understanding of the above statement, I think this is what you are looking for:

If you want to use the try with resources feature of Java 7 with the normal try-catch block prior to Java 7, then you must hand-code your finally block and also add proper exception handling catch while opening the resource.
The Java 7 try-with resources feature is essentially doing that for you.

The try-catch version for Mike's try-with-resources code posting



SCEA EE5, CSM, PMP, IBM OOAD with UML, SCDJWS, SCWCD, SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try-with-resources from Java tutorial