Java 7 New Exception Features - Multicatch Exceptions and Try with Resources

Java 7 introduces few new features to the exception handling mechanism. We will discuss them quickly here.

 

Java 7 Multi-Catch Exceptions

With java 7, you can catch multiple exceptions using a single catch block as:

    try {

      File file = new File("filename.txt");

      Scanner sc = new Scanner(file);

      throw new SQLException();

    }

    catch (FileNotFoundException | SQLException e) {

      System.out.println("FileNotFoundException or SQLException called!!!");

    }

 

Important Note: In a Java 7 multi-catch block, you cannot catch both child and parent exception together in a multi-catch block. For example, below code fragment won't compile.

catch (FileNotFoundException | IOException e1) {

      // TODO Auto-generated catch block

      e1.printStackTrace();

}

This is because all exceptions are mapped to a single variable and hence there is no use of mentioning the subclass and superclass separately.

However, if you are using the older syntax, you can catch them both in separate catch blocks, as in below code fragment:

catch (FileNotFoundException e) {

  System.out.println("FileNotFoundException called!!!");

 }

catch (IOException e) {

  System.out.println("IOException called!!!");

 

Java 7 Try-with-Resources

Finally block is usually used to close and release resources.

With the new java 7 syntax, you can declare your resources withing the try itself and  java automatically closes those resources (if they are not already closed) after the execution of the try block. 

    try (BufferedReader reader = 

        new BufferedReader(

            new FileReader(

        "filename.txt"))) 

        {

          // try block contents

    } catch (IOException e1) {

      // TODO Auto-generated catch block

      e1.printStackTrace();

    }

The resource type specified within the try should implement java.lang.AutoCloseable.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!