Advanced Java Programming - Old Questions

7. When does the finally block is mandatory in while handling exception? Describe with a suitable scenario. (5)

5 marks | Asked in 2077

Java finally block is a block used to execute important code such as closing the connection, etc. It is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.

  • finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
  • The important statements to be printed can be placed in the finally block.

Example:

class TestFinallyBlock {    

  public static void main(String args[]){    

  try{    

//below code do not throw any exception  

   int data=25/5;    

   System.out.println(data);    

  }    

//catch won't be executed  

  catch(NullPointerException e){  

System.out.println(e);  

}    

//executed regardless of exception occurred or not  

 finally {  

System.out.println("finally block is always executed ");  

}      

System.out.println("rest of the code...");    

  }    

}