Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Catch and Finally Block.

 
prashkumar darekar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is lot of confusion between lot of professionals about Catch and Finally Block.I want to know in Try-Catch-Finally ,whether Catch block is compulsory to write or Finally block is compulsory.In other words whether Catch block always follow the Try block or Finally block always follow Try block.I found out that in lot of books lot of authors have different opinion about it also exam simulators' opinions are also different from each other.Can anybody give me firm word about this.
Thank you,
Prash Kumar
 
shruthi vijayakumar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Catch Block is compulsary for Try block. Try block should have one Catch block and can have more than one Catch block. Finally block is optional. Finally block will get executed if you get unexpected exception in Try block

If you want more details, go through the following link

http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i do not know about the conflicts in programmers regarding catch and finally blocks. in context to your other questions, a try block must always be followed by either catch block or finally block. finally block is always executed(if present) whether exception is thrown or not. if exception is not thrown, then after statements in try block are executed , all the statements in finally block are executed. however , if exception occurs, then all the further statements in try block are skipped and control is transferred to the first catch block that catches the specified exception. then after catch block , finally block is executed. as a note, finally block is used to close the i/o, db resources that you have used. catch block would be inefficient for closing opened resources because then you have to specify code in every catch block which would result in code duplicacy.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shruthi vijayakumar wrote:Catch Block is compulsary for Try block. Try block should have one Catch block and can have more than one Catch block. Finally block is optional.

Try should have either a catch or finally. Catch block is not mandatory.
 
Stephan van Hulst
Bartender
Posts: 6337
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, with the Java 1.7 feature try-with-resources you don't even need any catch or finally clauses, if you specify AutoClosable resources in the try clause:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic