| Author |
Catch and Finally Block.
|
prashkumar darekar
Greenhorn
Joined: Apr 01, 2012
Posts: 2
|
|
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
Joined: Jan 24, 2012
Posts: 9
|
|
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
Joined: Apr 04, 2012
Posts: 868
|
|
|
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.
|
OCPJP 6(100 %) OCEWCD 6(91 %)
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
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
Joined: Sep 20, 2010
Posts: 3051
|
|
|
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:
|
 |
 |
|
|
subject: Catch and Finally Block.
|
|
|