Use of finally
Use of finally
Sometimes when an exception is raised ,the rest of statements in try block are ignored.Sometimes it is necessry to process certain statements,no matter whether an exception is raised or not.
A finally block encloses code that is always executed at some point after the
try block, whether an exception was thrown or not. Even if there is a return
statement in the try block, the finally block executes right after the return
statement is encountered, and before the return executes.
This is the right place to close your files, release your network sockets, and
perform any other work your code requires. If the try block executes with
no exception, the finally block is executed just after the try block
completes. If there was an exception occured, the finally block executes
immediately after the proper catch block completes.
Remember:-
1.Finally blocks are not mandatory in exception handling.
2.There can be only One finally block for a try.
3.finally can follow try that is finally can exist without catch as follows
try{
//do something
}
finally{
//Handle here
}
4.No code can be placed in between try catch.
5.No code can be placed between try finally.
6.If finally is to be placed in after try containing catche(s) then finally must follow last catch statemet.
Example:-
try{
opensomeFile();
writeanyFile(); //may result in exception
}
catch(Exception.....){
process the exception
}
finally{
closeFile();
}
In the above example we have to close the file irrespective of whether the exception is occured or not.You can place the code in both ty and catch blocks.But assume a situation where
exception is thrown before closing that file and we have no catch for exception raised.
our file will remain open.Thus in finally block we put the code which will be executed all the times regardless of whetehr an exception is raised or not.


















0 comments:
Post a Comment
Post a Comment