Enhanced Exception Handling-Java7 Feature

4
1496

Java 7.0 has introduced a couple of enhancements for exceptional handling functionality. We have seen another feature of Java 7 already which is having Strings in switch-case statements :

In this post we will cover the Exception Handling enhancements done in Java 7, which are :

1) Catching Multiple Exception Type

2) Try with resources

Let’s look at these features one by one.

Catching Multiple Exception Type

This feature gives the capability to a developer to catch multiple exceptions in a single catch clause using a pipe ( | ). Using this should be pretty simple but to understand this completely, let’s look at the traditional way of catching multiple exceptions. So before Java 7.0 we use to have code like below:

try{
 // do some code like making DB connection
 Statement statement = null;
 statement.execute("Select * from  goyalsbitTable");

 //Read a file
 BufferedReader reader = new  BufferedReader(new  FileReader("samplefile.txt"));
 String line = reader.readLine();
 reader.close();
}catch(SQLException e) {
   System.out.println("Exception " + e);
} catch(IOException e) {
   System.out.println("Exception " + e);
} catch(Exception e) {
   System.out.println("Exception " + e);
}

Now this catch clause will keep on increasing based on our code and the relevant exceptions. Java 7.0 makes this process simpler and more readable by allowing multiple catch statements to be written in single catch clause.

package com.gb.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;

public class SimpleExceptionHandling {

public static void main(String args []){

try{
 // do some code like making DB connection
 Statement statement = null;
 statement.execute("Select * from goyalsbitTable");

 //Read a file
 BufferedReader reader = new BufferedReader(new  FileReader("samplefile.txt"));
 String line = reader.readLine();
 reader.close();
}catch(SQLException | IOException e) {
   System.out.println("Exception " + e);
 }catch(Exception e) {
   System.out.println("Exception " + e);
  }
 }
}

This is a simple but important enhancement but as we know everything comes with price, so we do have one basic rule here too for its implementation :

The exception value is final, and we can’t assign the variable to some other value in the catch.

2) Try-With-Resources

Also known as automatic resource management, this feature brings another important add-on to exception handling. Normally whenever we do a resource management like DB management, IO resources management etc., we have to close the connections / resources in finally block (yes.. yes.. I know it can be closed in try block too, but the best place is finally block) ignoring which can bring instability in the code or nu-necessary resource consumption.

Now with automatic resource management we don’t have to worry about it. Below is the general syntax for it :

try (resource-specification)
{
 // do some code
}

We initialize a resource in try clause inside a parenthesis (). This will ensure that each resource is closed at the end of statement; we don’t need to explicitly close the resource here in try or finally block.

So to see an example, the same traditional code can now be written as:

try(FileInputStream input = new FileInputStream("goyalsbit.txt")) {
  int data = input.read();
}

When the try block finishes the FileInputStream will be closed automatically. We can also declare multiple resources inside this try clause. Let’s see this in below example

try(FileInputStream input = new FileInputStream("file.txt");
    BufferedInputStream bufferedInput = new BufferedInputStream(input);
    int data = bufferedInput.read();)

So as we have seen here we declared two resources in try clause here and both of these resources will be closed automatically when execution leaves the try block. The order of closing the resources will be reverse of the order in which they are created / listed inside the parentheses. First the BufferedInputStream will be closed and then the FileInputStream.

Now let’s understand the concept behind this functionality. Any object that implements java.lang.AutoClosable interface can be passed as a parameter to try statement. The only method in Auto-closeable is close which gets automatically invoked at run-time. Few important points to notice:

  • Classes that implements Auto-closeable must be used as a resource in try-with-resources, else we will get compilation error.
  • In try-with-resources on exception, before going to catch the close statements will be executed.
  • Resource declared in try gets instantiated just before the start of the try-block.
  • We can also implement an auto-closeable interface
  • Few of classes which implement this interface but not limited to FileInputSteam, FileOutputSteam, InputSteam, OutputStream, StringReader, Write, Selector, ServerSocket.

References:
https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html

Previous articleEclipse Installation – Step by Step Guide
Next articleFitNesse Step by Step Guide
Rahul Goel has 8+ years of experience in IT industry working on design & development of web based applications in Java /JEE technology stack. He posses various business domains knowledge like HealthCare, Banking & Finance, E Commerce, Retail, and Security. Rahul is passionate about cricket, traveling and his technical writing.

4 COMMENTS

  1. well explained
    may consider adding the following explanation
    catch(SQLException | Exception )
    error since SQLException is subclass of exception and SQLException part becomes superfluous
    similarly for the first part error
    when we try to catch an exception which has already been caught

LEAVE A REPLY