Finally

Exception alter the path of execution. for example if in program we have opened a file and performing some operation. At the end file must be closed.


Simple program structure for file handling:



 main method() 
{
open file
perform operation
close file
}

Now assume if during performing operation on file if any exception occurred then program terminates abruptly. File close operation won't be executed. Hence file left open.


Above problem can be rectified by using try-catch block

Try-catch use


 main method()
{
try
{
open file
perform operation
}
catch(Exception e)
{
close file
}
}

Above program now works fine in case of exception. If exception will occur control will be transferred to catch block and file will be closed.



Now assume if no exception occurred then control won't be transferred to catch block. Again same problem file will be left open.



finally used for situation when programmer wants to execute some piece of code in every condition. finally comes with try block. A try block can have many catch plus one finally block.


Syntax:

  try
{

}
catch( <Exception type >)
{

}
finally
{
< Code always get executed >
}

finally block always be executed, whether exception is there or not.