Showing posts with label Finally. Show all posts
Showing posts with label Finally. Show all posts

Try, Catch and Finally in Java

In this tutorial we will see about try, catch and finally blocks in Java. When we talk about these 3 blocks its come under Exception Handling and one on the finest feature in Java to handle both checked and UN-checked exceptions.

  • try() - Try block used to hold statements which may cause exception at compile time or at run-time. Those statements will be surrounded with try block.
  • catch() - Catch block used to catch if any exception occurred in try block statements. Basically list of exceptions will be specified in the catch statement as like given below examples. Before Java 7 each exception should be specified in separate catch blocks and need to catched. But in Java 7 we have got a cool feature to use multi-catch exception handling. Please refer to our earlier tutorial for Java 7 multi-catch
  • finally() - Finally block will execute no matter whether if any exception occurred or not occurred, always finally block will be executed except 
    • - if there are any infinite looping in try or catch block
    • - or if System.exit statement present in try or catch block.
There are few interview questions were interviewer will be asked,

1. Try block can be without catch block?
Answer: Yes, but finally block is necessary in that case. 

2. Try and catch block can be without finally block?
Answer: Yes

3. Finally block can be without try or catch?
Answer: No, finally must be placed with try or try & catch block. 

4. Single try block can have multiple catch blocks?
Answer: Yes

5. Can we have multiple finally blocks?
Answer: No, for single try and catch there must be only 1 finally block.


Lets see few examples

EXAMPLE - 1


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 20;
  
  }catch (NumberFormatException e) {
   System.out.println("NumberFormatException occured !!!");
   return 5;
  
  }catch (Exception e) {
   System.out.println("Exception occured !!!");
   return 30;
  
  }finally{
   return 10;
  }
 }
}

OUTPUT:


NUMBER : 10


EXAMPLE - 2


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 50;
  }finally{
   return 100;
  }
 }
}

OUTPUT:


NUMBER : 100


EXAMPLE - 3


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  String name = null;
  myFunction(name);  
 }
 
 public static void myFunction(String name){
  try{
   System.out.println("LENGTH: "+name.length());
   System.out.println("NAME: "+name);
  
  }catch (NullPointerException e) {
   System.out.println("NullPointerException occured !!!");
  
  }finally{
   System.out.println("Finally Executed...");
  }
  System.out.println("Function finished ...");
 }
}

OUTPUT:


NullPointerException occured !!!
Finally Executed...
Function finished ...







What is the difference between final, finally and finalize in Java?

 
In this tutorial we will see about difference between final, finally and finalize in Java. 

final - final is a keyword in Java used to indicate whether variable, method or class can be a final. 
Once a variable set as final then the value can't be changed. 
Once a method set as final then the method can't be override d.
Once a class set as final then the class can't be inherited or extended by other classes.

finally - finally is block used in exception handling. Finally can be followed by try-catch or without catch block. But once we place a finally block then it will be executed always. 

finalize - finalize is a method and used in garbage collection. finalize() method will be invoked just before the Object is garbage collected. It will be called automatically by the JVM on the basis of resource reallocating.  Even programmers can call finalize method by using System.gc(); but vendor to vendor (Different OS) will change and not sure 100% finalize method will be called. 

Lets see small program for final, finally and finalize



Example for final:


// Final class
public final class FinalTest {
 
 // Final member variable
 private final int id = 100; 
 
 // Final method
 public final void getValue(){
  System.out.println("Inside final method");
 }
}




Example for finally:


public final class FinallyTest {
 
 public int getValue1(){
  try{
   return 10;
  }catch(NumberFormatException e){
   e.printStackTrace();
  }finally{
   return 20;
  }
 }
 
 public int getValue2(){
  try{
   return 100;
  }finally{
   return 200;
  }
 }
 
 public static void main(String[] args) {
  FinallyTest obj = new FinallyTest();
  
  int val1 = obj.getValue1();
  int val2 = obj.getValue2();
  
  System.out.println("VALUE-1 : "+val1);
  System.out.println("VALUE-2 : "+val2);
 }
}




Example for finalize:


public final class FinalizeTest {
 
 @Override
 protected void finalize() throws Throwable {
  System.out.println("Inside Finalize method");
  super.finalize();
 }
 
 public static void main(String[] args) {
  try{
   FinalizeTest obj = new FinalizeTest();
  }catch (Exception e) {
   e.printStackTrace();
  }
  System.gc();
 }
}