Open In App

Version Enhancements in Exception Handling introduced in Java SE 7

Last Updated : 04 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, the enhancements made by Oracle in version 1.7, along with its implementation, has been discussed.

As a part of 1.7 version enhancement, in Exception Handling, the following two concepts have been introduced by Oracle:

  1. Try with resources.
  2. Multiple catch blocks.

Try with resources

Until version 1.6, it was highly recommended to write finally block to close all the resources which are open as a part of the try block.

For example:




// Java program to illustrate cleaning of
// resources before Java 7
  
import java.io.*;
import java.util.*;
  
class Resource {
    public static void main(String args[])
    {
        BufferedReader br = null;
        String str = " ";
  
        System.out.println(
            "Enter the file path");
        br
            = new BufferedReader(
                new InputStreamReader(
                    System.in));
  
        try {
  
            str = br.readLine();
  
            String s;
  
            // file resource
            br
                = new BufferedReader(
                    new FileReader(str));
  
            while ((s = br.readLine()) != null) {
                // print all the lines
                // in the text file
                System.out.println(s);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
  
        // This part was compulsory before Java 7
        // but with the introduction of
        // try with resource in Java 7
        // this part is optional now.
        finally {
            try {
                if (br != null)
  
                    // closing the resource
                    // in 'finally' block
                    br.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}


Output:

hello
java

Advantage of try with recourses:

  1. The main advantage of try with resources is that the resources which were opened as the part of try block will be closed automatically once the control reaches the end of the try block either normally or abnormally. Hence, we are not required to close it explicitly. Therefore, the complexity of programming will be reduced.
  2. We can declare any number of resources but all these resources should be separated with semicolon(;)
    try(R1;R2;R3)
    {
    - - - - - - -
    - - - - - - -
    }
    
  3. All the resources should be AutoCloseable resources. A resource is said to be auto closeable if and only if the corresponding class
    implements the java.lang.AutoCloseable interface either directly or indirectly.
    For example, all the database related, network-related and file IO related resources already implemented AutoCloseable interface.
  4. All resources reference variables are implicitly final and hence we can’t perform reassignment within the try block. For example, in the code below, we are reassigning the value of br for which we get a compile-time error.




    try (BufferedReader br = new BufferedReader(new FileReader("abc.txt"))) {
        br = new BufferedReader(new FileReader("abc.txt"));
    }

    
    

  5. Until version 1.6, try should be followed by either catch or finally but 1.7 version we can take only try with resources without a catch or finally statement.
    try(R)
    {  //valid
    }
    

Below is the implementation of the enhanced try-catch block:




// Try opening a file
try (bufferedReader br = new BufferedReader(new FileReader("abc.txt"))) {
}
  
// Catch an exception
catch (IOException e) { // handling code }
  
// After the execution of try and catch is completed
// the file is closed automatically by Java


Multiple catch blocks:

Until version 1.6, if we wish to handle multiple exceptions for the same try block, we had to define all the exceptions in multiple catch statements.

For example:




// For this try block
try {
    -------- - -------- -
}
  
// Catching Arithmetic Exception
catch (ArithmeticException e) {
    e.printStackTrace();
}
  
// Catching Nullpointer Exception
catch (e) {
    e.printStackTrace();
}
  
// Catching Class Cast Exception
catch (ClassCastException e) {
    System.out.println(e.getMessage());
}
  
// Catching IOException
catch (IOException e) {
    System.out.println(e.getMessage());
}


To overcome this problem, the “Multi catch block” concept is introduced in 1.7 version. Therefore, all the exceptions can be handled with a single catch statement.

Below is the implementation of the multi-catch statement:




try {
    ------ - ------ -
}
catch (ArithmeticException | NullpointerException
       | ClassCastException | IOException e) {
    System.out.println(e.getMessage());
}


Note: In multi-catch block, there should not be any relation between Exception types (either child to parent or parent to child or the same type.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads