Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Catch multiple exceptions


Catch multiple exceptions is a Java 1.7 feature, we can handle multiple types of exceptions in a single catch block.
Let’s we check the difference before java 1.7 version and from java 1.7 version

Before Java 1.7 version


 In Java 1.6 and early versions, if multiple exceptions occur in try block then we use separate catch block for every exception handling even though those exceptions have same handling code.

The drawbacks with multiple catch blocks:
=> It increases the program code and decreases the readability of the program.
=> We must write catch block for every exception handling.
=> It is complexity to the programmer.

In this program, in try block occurs different type of exceptions that we handled in separate catch block for every exception. Assume that first two catch blocks having same handling code but we handled in the separate catch blocks and also second two catch blocks.


package com.exceptions;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MultiCatchTest {
       public static void main(String[] args) {       
              try {
                     PrintWriter pw=new PrintWriter("abc.txt");
                     int i=10/0;
              }
              catch (FileNotFoundException e) {
                     System.out.println(e);
              }
              catch (ArithmeticException ae) {
                     System.out.println(ae);
              }
              catch (NullPointerException e) {               
                     e.printStackTrace();             
              }
              catch (ClassCastException e) {                 
                     e.printStackTrace();             
           }
       }
}


From Java 1.7 version: catch multiple exceptions


From Java 1.7 version onwards we can write single catch block to handle multiple types of exceptions.
Every exception class is separated by vertical bar ( | ) in catch block

Advantages of catch multiple exceptions:
=> It decreases the program code and increases the readability of the program.
=> Easy to write for the developer.


package com.exceptions;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MultiCatchTest {
       public static void main(String[] args) {       
              try {
                     PrintWriter pw=new PrintWriter("abc.txt");
                     int i=10/0;
              }
              catch (FileNotFoundException | ArithmeticException e) {
                     System.out.println(e);
              }            
              catch (NullPointerException | ClassCastException e) {               
                     e.printStackTrace();             
              }            
       }
}


No choice to write parent and child exception or same exception classes in the same catch block.

catch (ArithmeticException | Exception e) {
              System.out.println(e);
       }
OR

catch (ArithmeticException | ArithmeticException e) {
              System.out.println(e);
       }

In this case, we will get compile time error as

The exception ArithmeticException is already caught by the alternative Exception



try with Resources


In Java try with resources, a resource is an object it may be File resource or Database connection resource or Network connection resource and that resource must be closed after completed the program.

Before Java 1.7 version


In Java 1.6 or early version, try block is used to open the resource and after completed the usage of the resource we must close that resource explicitly in a finally block.


package com.exceptions;
public class Test {
       try{
              //Open resources like File resource, Database connection resource etc.
       }
       catch (IOException e) {
              // Handling Exceptions
       }finally{
              // Close resources
       }
}


Example for close resource in finally block


In this program,  we created a resource BufferedReader object and pointing it myfile.txt. If any choice occurs exception that should handle by the catch block and after completed the usage of resource we closed resource explicitly in finally block.

The main drawbacks are here:
=> The length of the program code increase and readability of program decrease
=> Programmer must close the resources explicitly
=> More complexity to the programmer.


package com.exceptions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Test {
       public static void main(String[] args) {
              BufferedReader br = null;
              try {
                     br = new BufferedReader(new FileReader("D:\\myfile.txt"));
                     System.out.println(br.readLine());
              }
              catch (IOException e) {
                     System.out.println(e);
              }
              finally {
                    
                           if (br != null)
                                  try {
                                         br.close();
                                  } catch (IOException e) {
                                         System.out.println(e);
                                  }                   
              }
       }
}


From Java 1.7 version


From Java 1.7 version onwards we don’t need to close the resource explicitly in the finally block, resources are closed automatically after executed the try and catch blocks.


     try(/* Open resources here */){
           // Use resources
       } catch (IOException e) {
              // Handling Exception
       }
      

In this program, we don’t need to close resource explicitly in finally block, what are the resources are opened in try those resources closed automatically after executed the try and catch blocks.

The main use of try with resources:
=> The length of the program code decrease and readability of the program increase
=> Developer no need to close the resources explicitly
=> No need of finally block and easy to write for developer

try with resource example



package com.exceptions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Test {
       public static void main(String[] args) {       
              try(BufferedReader br
                           = new BufferedReader(new FileReader("D:\\myfile.txt"))) {                 
                     String line=br.readLine();
                     while(line!=null){
                           System.out.println(line);
                           line=br.readLine();
                     }
              }
              catch (IOException e) {
                     System.out.println(e);
              }            
       }
}


Try with multiple resources


We can open multiple resources in the try-resources statement separated by a semicolon(;).


try(/*Resource1; Resource2; Resource3*/){      
       //use resources
}
catch(IOException e){
       //handle exceptions
}


Example for a try with multiple resources:


package com.exceptions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class TryWithResources {
       public static void main(String[] args) {       
              try(BufferedReader br
                           = new BufferedReader(new FileReader("D:\\myfile.txt"));
                           PrintWriter pw=new PrintWriter("D:\\newfile.txt")   ) {
                     //we can read a file and write a file
              }
              catch (IOException e) {
                     System.out.println(e);
              }            
       }
}