Version Enhancements in Exception Handling introduced in Java SE 7

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
            }
        }
    }
}

chevron_right


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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.