Definition of Finally keyword:

 

The finally keyword ensures that all the statements present inside the block finally block are compulsory executed.

What is the need of finally block?

Sometimes, some statements inside a try block need to be executed compulsorily whether exceptions occur or not.

 

Example:

Try

{

Get connection to a printer

=======

Con .close ()

}

Catch (Exception e)

{

System. Out. Prinln(e);

}

 

Explanation:

  • Now after gettingconnectionto a printer, let us assume that an exception is generated in one of the statements after getting the connection. Then the control comes out of the try without executing the rest of the statements.
  • The last statement inside try block iscon. Close (). This statement will not be executed if an exception occurs before this.
  • Now the scenario is, the resource (printer) has been allocated to our system, but it is not released. This is infective resource management.
  • To overcome this problem, may people suggest one solution i.e. to write con. Close () outside try catch. Not only con. Close (), but any statement which needs to be compulsorily executed is supported to be placed outside try catch.
  • In fact, this solution works well, but it is not at all recommended.
  • In order to maintain modularity, all the statements present intryblock that are to be compulsorily executed irrespective of expressions, are to be placed in a separate block finally.
  • Finally is a block associated with try block just as the catchblock.
  • After the execution of either try or catch blocks, it then executes thefinallyblock and then goes for the rest of the statements present in the function, outside the try-catch.
  • Finallyblock cannot exist individually without a try block.
  • A try block can have any number of catch blocks but it can have only one finally block.

 

Finally Keyword Homework Help