Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try without catch?

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Under what circumstances would we use a try block
without a catch block?
Would a finally block be required in this situation?
Thanks!
Drew
 
Angela Narain
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes , the try block has to followed by atleast a catch ( more than one if required ) OR a
finally block.
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, but when would you actually use a try/finally without a catch?
try{
// code that might throw an exception
}
finally{
// do something here
}
If the code in the try block throws a checked exception wouldn't it require the use of a catch block anyway?
Regards,
Drew
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Drew!
I'll try to illustrate this w/ a lil snippet:

So we can delegate error handling to higher scope, but yet we can do some things in finally blocks. Snippet has the idea but isnt very good example for this.
------------------
Antti Barck
It Solutions Consultant -- NSD Oy
Sun Certified Programmer for the Java™ 2 Platform
 
Cameron Park
Ranch Hand
Posts: 371
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use try/finally without a catch block. Usually, you just want to release some non-memory resources allocated in the try block, and you want to make sure that these resources will be released no matter what. You use try/finally block to accomplish that.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Helo Cameron!
That was much better example.
------------------
Antti Barck
It Solutions Consultant -- NSD Oy
Sun Certified Programmer for the Java™ 2 Platform
 
Muhammad Farooq
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just want to add one more thing, if there is no catch block or specific or related catch block (of super class of the exception raised) then the Exception is said to be uncaught and method terminate after final block.
--Farooq
[This message has been edited by Muhammad Farooq (edited August 27, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic