Showing posts with label try catch. Show all posts
Showing posts with label try catch. 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 ...







Java 7 - try-with-resources

In earlier tutorials we have seen couple of Java 7 features like Underscore in numeric literals, Switch Case with non-primitive data-type and Exception handling with multi-catch.

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.
 

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.
 



public class MyOldFileHandling {
    public static void main(String[] arg){
        FileInputStream fstream = null;
        DataInputStream istream = null;
        BufferedReader breader = null;
        try {            
            fstream = new FileInputStream("test.txt");
            istream = new DataInputStream(fstream);
            breader = new BufferedReader(new InputStreamReader(istream));
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                /* 
                 * Explicitly all resources need to be closed in 
                 * earlier java versions 
                */

                if(fstream != null)fstream.close();
                if(istream != null)istream.close();
                if(breader != null)breader.close();
            }catch(IOException ioe){
                ioe.printStackTrace();;
            }
        }
    }
}



In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. 

But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.
 



try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}



Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.
 



try(FileInputStreamfstream = new FileInputStream("test.txt");
    DataInputStream istream = new DataInputStream(fstream);
    BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {
.
.
}

Below example will show same above program will be handled using try-with-resource using Java 7.
 



public class MyNewFileHandling {
        public static void main(String[] arg){
        
        try (FileInputStream fstream = new FileInputStream("test.txt");            
             DataInputStream istream = new DataInputStream(fstream);
             BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {            
            
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}