• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Suppressed Exceptions

 
Greenhorn
Posts: 5
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have Just studied this topic and for what I understood is that the close() method can throw an exception in addition to the try block itself.  Also, these exceptions are saved in an suppressed array.

By doing this test, I got what I expected in the output:


Output:

But when I remove one object declaration of the <try-with-resources> for some reason, the "finally" is printed first and I just can not understand why


I thought the output will be:

Hope you can help me!
 
Mario Segovia
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry,

I thought this would be the output:


try
suppresed: java.io.IOException: closing1
finally
 
Saloon Keeper
Posts: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When I run the second version of your code I get:
 
Mario Segovia
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Stephan van Hulst, turns out that if in the print statement you use out instead of err the output is the expected. Do not know why if you keep two objects in the try-with-resources and the err in the print statement it works fine.
 
Stephan van Hulst
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah I see.

The reason is that when you write to two different streams, it is not guaranteed that strings written to one stream first are flushed to the output device before strings written to another stream.

If you want strings to appear in the order that you print them in, you must always print them to the same stream.
 
"I know this defies the law of gravity... but I never studied law." -B. Bunny Defiant tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic