• Post Reply Bookmark Topic Watch Topic
  • New Topic

Try Catch blocks in a Finally block  RSS feed

 
Benedict Wong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've stumbled upon something that intrigues me again. I saw some code that actually had try catch blocks in a finally block, something like:


I understand that a finally block is supposed to contain cleanup code that executes regardless of whether any exceptions are thrown. So to have try catch blocks for cleanup code, I'm guessing the cleanup code must contain something rather complex that exceptions could occur there?
 
Dave Tolls
Ranch Foreman
Posts: 3065
37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before they introduced try-with-resources you would see this with database interaction code (JDBC):


So yes, it is because the cleaning up of the resource can encounter an issue.  Though in most cases all you can do is log the issue.
 
Benedict Wong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dave, that explains! I will keep your answer in mind when I reach the topic on Databases.
 
Dave Tolls
Ranch Foreman
Posts: 3065
37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We now have try-with-resources, though, so the above is generally:


It no longer needs the finally to close the resource declared in the try.
 
Benedict Wong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right, Dave. I'm reading that section in Java SE8. Seems like there are situations when normal try catch is still necessary. No wonder it is essential to learn both approaches.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!